Given two integers and . The task is to find the Nth term which is divisible by either of or .
Input : a = 2, b = 5, N = 10 Output : 16 Input : a = 3, b = 7, N = 25 Output : 57
Naive Approach : A simple approach is to traverse over all the terms starting from 1 until we find the desired Nth term which is divisible by either of or . This solution has time complexity of O(N).
Efficient Approach : The idea is to use Binary search. Here we can calculate how many numbers from 1 to are divisible by either a or b by using formula:
All the multiples of lcm(a, b) will be divisible by both and so we need to remove these terms. Now if the number of divisible terms is less than N we will increase the low position of binary search otherwise decrease high until number of divisible terms is equal to N.
Below is the implementation of the above idea :
- Find the Nth term divisible by a or b or c
- Program to print all the numbers divisible by 3 and 5 for a given number
- Find the number closest to n and divisible by m
- Find the first natural number whose factorial is divisible by x
- Find an array element such that all elements are divisible by it
- Find set of m-elements with difference of any two elements is divisible by k
- Program to find GCD or HCF of two numbers
- Program to find LCM of two numbers
- Program to find HCF iteratively
- Program to find LCM of 2 numbers without using GCD
- Program to find LCM of two Fibonnaci Numbers
- Program to find largest element in an array
- Program to find GCD of floating point numbers
- Program to find the minimum (or maximum) element of an array
- Program to find GCD or HCF of two numbers using Middle School Procedure
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.