Nth number in a set of multiples of A , B or C | Function to return gcd of a and b ; Function to return the count of integers from the range [ 1 , num ] which are divisible by either a , b or c ; Calculate the number of terms divisible by a , b and c then remove the terms which are divisible by both ( a , b ) or ( b , c ) or ( c , a ) and then add the numbers which are divisible by a , b and c ; Function for binary search to find the nth term divisible by a , b or c ; Set low to 1 and high to LONG_MAX ; If the current term is less than n then we need to increase low to mid + 1 ; If current term is greater than equal to n then high = mid ; Driver code
function gcd ( a , b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } function divTermCount ( a , b , c , num ) { return parseInt ( ( ( num / a ) + ( num / b ) + ( num / c ) - ( num / ( ( a * b ) / gcd ( a , b ) ) ) - ( num / ( ( c * b ) / gcd ( c , b ) ) ) - ( num / ( ( a * c ) / gcd ( a , c ) ) ) + ( num / ( ( ( ( a * b ) / gcd ( a , b ) ) * c ) / gcd ( ( ( a * b ) / gcd ( a , b ) ) , c ) ) ) ) ) ; } function findNthTerm ( a , b , c , n ) { var low = 1 , high = Number . MAX_SAFE_INTEGER , mid ; while ( low < high ) { mid = low + ( high - low ) / 2 ; if ( divTermCount ( a , b , c , mid ) < n ) low = mid + 1 ; else high = mid ; } return low ; } var a = 2 , b = 3 , c = 5 , n = 100 ; document . write ( parseInt ( findNthTerm ( a , b , c , n ) ) ) ;