Print numbers such that no two consecutive numbers are co | Java implementation of the approach ; Function for Sieve of Eratosthenes ; Function to print the required sequence ; Store only the required primes ; Base condition ; First integer in the list ; Second integer in the list ; Third integer in the list ; Generate ( N - 1 ) th term ; Generate Nth term ; Modify first term ; Print the sequence ; Driver code
import java . util . * ; class GFG { static int MAX = 620000 ; static int [ ] prime = new int [ MAX ] ; static void Sieve ( ) { for ( int i = 2 ; i < MAX ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = 2 * i ; j < MAX ; j += i ) { prime [ j ] = 1 ; } } } } static void printSequence ( int n ) { Sieve ( ) ; Vector < Integer > v = new Vector < Integer > ( ) ; Vector < Integer > u = new Vector < Integer > ( ) ; for ( int i = 13 ; i < MAX ; i ++ ) { if ( prime [ i ] == 0 ) { v . add ( i ) ; } } if ( n == 3 ) { System . out . print ( 6 + " ▁ " + 10 + " ▁ " + 15 ) ; return ; } int k ; for ( k = 0 ; k < n - 2 ; k ++ ) { if ( k % 3 == 0 ) { u . add ( v . get ( k ) * 6 ) ; } else if ( k % 3 == 1 ) { u . add ( v . get ( k ) * 15 ) ; } else { u . add ( v . get ( k ) * 10 ) ; } } k -- ; u . add ( v . get ( k ) * 7 ) ; u . add ( 7 * 11 ) ; u . set ( 0 , u . get ( 0 ) * 11 ) ; for ( int i = 0 ; i < u . size ( ) ; i ++ ) { System . out . print ( u . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 4 ; printSequence ( n ) ; } }