Print all safe primes below N | Function to print first n safe primes ; Initialize all entries of integer array as 1. A value in prime [ i ] will finally be 0 if i is Not a prime , else 1 ; 0 and 1 are not primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; If i is prime ; 2 p + 1 ; If 2 p + 1 is also a prime then set prime [ 2 p + 1 ] = 2 ; i is a safe prime ; Driver code
function printSafePrimes ( n ) { let prime = new Array ( n + 1 ) ; for ( let i = 2 ; i <= n ; i ++ ) prime [ i ] = 1 ; prime [ 0 ] = prime [ 1 ] = 0 ; for ( let p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == 1 ) { for ( let i = p * 2 ; i <= n ; i += p ) prime [ i ] = 0 ; } } for ( let i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] != 0 ) { let temp = ( 2 * i ) + 1 ; if ( temp <= n && prime [ temp ] != 0 ) prime [ temp ] = 2 ; } } for ( let i = 5 ; i <= n ; i ++ ) if ( prime [ i ] == 2 ) document . write ( i + " " ) ; } let n = 20 ; printSafePrimes ( n ) ;