Alternate Primes till N | Java program to print all primes smaller than or equal to n using Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers ; for next prime to get printed ; Driver Code
class GFG { static void SieveOfEratosthenes ( int n ) { boolean [ ] prime = new boolean [ n + 1 ] ; for ( int i = 0 ; i < prime . length ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } boolean flag = true ; for ( int p = 2 ; p <= n ; p ++ ) { if ( prime [ p ] ) { if ( flag ) { System . out . print ( p + " ▁ " ) ; flag = false ; } else { flag = true ; } } } } public static void main ( String [ ] args ) { int n = 15 ; System . out . println ( " Following ▁ are ▁ the ▁ alternate " + " ▁ prime ▁ numbers ▁ smaller ▁ " + " than ▁ or ▁ equal ▁ to ▁ " + n ) ; SieveOfEratosthenes ( n ) ; } }