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
< ? php function printSafePrimes ( $ n ) { $ prime = array ( ) ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ prime [ $ i ] = 1 ; $ prime [ 0 ] = $ prime [ 1 ] = 0 ; for ( $ p = 2 ; $ p * $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] == 1 ) { for ( $ i = $ p * 2 ; $ i <= $ n ; $ i += $ p ) $ prime [ $ i ] = 0 ; } } for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) { if ( $ prime [ $ i ] != 0 ) { $ temp = ( 2 * $ i ) + 1 ; if ( $ temp <= $ n && $ prime [ $ temp ] != 0 ) $ prime [ $ temp ] = 2 ; } } for ( $ i = 5 ; $ i <= $ n ; $ i ++ ) if ( $ prime [ $ i ] == 2 ) echo $ i , " ▁ " ; } $ n = 20 ; printSafePrimes ( $ n ) ; ? >