Find out the prime numbers in the form of A + nB or B + nA | Javascript 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
function __gcd ( a , b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } function coprime ( a , b ) { if ( __gcd ( a , b ) == 1 ) return true ; else return false ; } function isPrime ( n ) { if ( n <= 1 ) return false ; if ( n == 2 n == 3 ) return true ; for ( let i = 2 ; i * i <= n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } function findNumbers ( a , b , n ) { let possible = true ; if ( ! coprime ( a , b ) ) possible = false ; let c1 = 1 ; let c2 = 1 ; let num1 , num2 ; let st = new Set ( ) ; if ( possible ) { while ( st . size != n ) { num1 = a + ( c1 * b ) ; if ( isPrime ( num1 ) ) { st . add ( num1 ) ; } c1 ++ ; num2 = b + ( c2 * a ) ; if ( isPrime ( num2 ) ) { st . add ( num2 ) ; } c2 ++ ; } st = [ ... st ] . sort ( ( a , b ) => a - b ) for ( let i of st ) document . write ( i + " " ) ; } else document . write ( " " ) ; } let a = 3 ; let b = 5 ; let n = 4 ; findNumbers ( a , b , n ) ;