Find out the prime numbers in the form of A + nB or B + nA | Java implementation of the 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
import java . util . * ; class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static boolean coprime ( int a , int b ) { if ( __gcd ( a , b ) == 1 ) return true ; else return false ; } static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n == 2 n == 3 ) return true ; for ( int i = 2 ; i * i <= n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } static void findNumbers ( int a , int b , int n ) { boolean possible = true ; if ( ! coprime ( a , b ) ) possible = false ; int c1 = 1 ; int c2 = 1 ; int num1 , num2 ; HashSet < Integer > st = new HashSet < Integer > ( ) ; if ( possible ) { while ( ( int ) 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 ++ ; } for ( int i : st ) System . out . print ( i + " ▁ " ) ; } else System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int a = 3 ; int b = 5 ; int n = 4 ; findNumbers ( a , b , n ) ; } }