Print numbers such that no two consecutive numbers are co | Java implementation of the approach ; Function to generate Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Add the prime numbers to the array b ; Function to return the gcd of a and b ; Function to print the required sequence of integers ; Including the primes in a series of primes which will be later multiplied ; This is done to mark a product as existing ; Maximum number of primes that we consider ; For different interval ; For different starting index of jump ; For storing the numbers ; Checking for occurrence of a product . Also checking for the same prime occurring consecutively ; Including the primes in a series of primes which will be later multiplied ; Driver Code
import java . util . * ; class GFG { static int limit = 1000000000 ; static int MAX_PRIME = 2000000 ; static int MAX = 1000000 ; static int I_MAX = 50000 ; static HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; static int [ ] b = new int [ MAX ] ; static int [ ] p = new int [ MAX ] ; static int j = 0 ; static boolean [ ] prime = new boolean [ MAX_PRIME + 1 ] ; static void SieveOfEratosthenes ( int n ) { for ( int i = 0 ; i < MAX_PRIME + 1 ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n ; p ++ ) { if ( prime [ p ] ) { b [ j ++ ] = p ; } } } static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static void printSeries ( int n ) { SieveOfEratosthenes ( MAX_PRIME ) ; int i , g , k , l , m , d ; int [ ] ar = new int [ I_MAX + 2 ] ; for ( i = 0 ; i < j ; i ++ ) { if ( ( b [ i ] * b [ i + 1 ] ) > limit ) break ; p [ i ] = b [ i ] ; mp . put ( b [ i ] * b [ i + 1 ] , 1 ) ; } d = 550 ; boolean flag = false ; for ( k = 2 ; ( k < d - 1 ) && ! flag ; k ++ ) { for ( m = 2 ; ( m < d ) && ! flag ; m ++ ) { for ( l = m + k ; l < d ; l += k ) { if ( ( ( b [ l ] * b [ l + k ] ) < limit ) && mp . containsKey ( b [ l ] * b [ l + k ] ) && mp . containsKey ( p [ i - 1 ] * b [ l ] ) && ( l + k ) < d && p [ i - 1 ] != b [ l + k ] && p [ i - 1 ] != b [ l ] && mp . get ( b [ l ] * b [ l + k ] ) != 1 ) { if ( mp . get ( p [ i - 1 ] * b [ l ] ) != 1 ) { p [ i ] = b [ l ] ; mp . put ( p [ i - 1 ] * b [ l ] , 1 ) ; i ++ ; } } if ( i >= I_MAX ) { flag = true ; break ; } } } } for ( i = 0 ; i < n ; i ++ ) ar [ i ] = p [ i ] * p [ i + 1 ] ; for ( i = 0 ; i < n - 1 ; i ++ ) System . out . print ( ar [ i ] + " ▁ " ) ; g = gcd ( ar [ n - 1 ] , ar [ n - 2 ] ) ; System . out . print ( g * 2 ) ; } public static void main ( String [ ] args ) { int n = 4 ; printSeries ( n ) ; } }