text: Nth number in a set of multiples of A , B or C | Python3 program to find nth term divisible by 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
code: import sys NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def divTermCount ( a , b , c , num ) : NEW_LINE INDENT return ( ( 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 * c ) / gcd ( gcd ( a , b ) , c ) ) ) ) ; NEW_LINE DEDENT def findNthTerm ( a , b , c , n ) : NEW_LINE INDENT low = 1 ; high = sys . maxsize ; mid = 0 ; NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = low + ( high - low ) / 2 ; NEW_LINE if ( divTermCount ( a , b , c , mid ) < n ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = mid ; NEW_LINE DEDENT DEDENT return int ( low ) ; NEW_LINE DEDENT a = 2 ; b = 3 ; c = 5 ; n = 100 ; NEW_LINE print ( findNthTerm ( a , b , c , n ) ) ; NEW_LINE