Find out the prime numbers in the form of A + nB or B + nA | Python3 implementation of the above approach ; Utility function to check whether two numbers is co - prime or not ; Utility function to check whether a number is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; finding the Prime numbers ; Checking whether given numbers are co - prime or not ; To store the N primes ; If ' possible ' is true ; Printing n numbers of prime ; checking the form of a + nb ; Checking the form of b + na ; If ' possible ' is false return - 1 ; Driver Code
from math import gcd , sqrt NEW_LINE def coprime ( a , b ) : NEW_LINE INDENT if ( gcd ( a , b ) == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( n == 2 or n == 3 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def findNumbers ( a , b , n ) : NEW_LINE INDENT possible = True ; NEW_LINE if ( not coprime ( a , b ) ) : NEW_LINE INDENT possible = False ; NEW_LINE DEDENT c1 = 1 ; NEW_LINE c2 = 1 ; NEW_LINE num1 = 0 ; NEW_LINE num2 = 0 ; NEW_LINE st = set ( ) ; NEW_LINE if ( possible ) : NEW_LINE INDENT while ( len ( st ) != n ) : NEW_LINE INDENT num1 = a + ( c1 * b ) ; NEW_LINE if ( isPrime ( num1 ) ) : NEW_LINE INDENT st . add ( num1 ) ; NEW_LINE DEDENT c1 += 1 ; NEW_LINE num2 = b + ( c2 * a ) ; NEW_LINE if ( isPrime ( num2 ) ) : NEW_LINE INDENT st . add ( num2 ) ; NEW_LINE DEDENT c2 += 1 ; NEW_LINE DEDENT for i in st : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 ; NEW_LINE b = 5 ; NEW_LINE n = 4 ; NEW_LINE findNumbers ( a , b , n ) ; NEW_LINE DEDENT