Find count of Almost Prime numbers from 1 to N | Java program to count almost prime numbers from 1 to n ; 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 ; Function to count almost prime numbers from 1 to n ; to store required answer ; 6 is first almost prime number ; to count prime factors ; if it is perfect square ; if I is almost prime number ; Driver code
import java . io . * ; class GFG { static int N = 100005 ; static boolean prime [ ] = new boolean [ N ] ; static void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < N ; i ++ ) prime [ i ] = true ; prime [ 1 ] = false ; for ( int p = 2 ; p * p < N ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i < N ; i += p ) prime [ i ] = false ; } } } static int almostPrimes ( int n ) { int ans = 0 ; for ( int i = 6 ; i <= n ; i ++ ) { int c = 0 ; for ( int j = 2 ; j * j <= i ; j ++ ) { if ( i % j == 0 ) { if ( j * j == i ) { if ( prime [ j ] ) c ++ ; } else { if ( prime [ j ] ) c ++ ; if ( prime [ i / j ] ) c ++ ; } } } if ( c == 2 ) ans ++ ; } return ans ; } public static void main ( String [ ] args ) { SieveOfEratosthenes ( ) ; int n = 21 ; System . out . println ( almostPrimes ( n ) ) ; } }