Find the sum of all Truncatable primes below N | PHP implementation of the approach ; To check if a number is prime or not ; Sieve of Eratosthenes function to find all prime numbers ; Function to return the sum of all truncatable primes below n ; To store the required sum ; Check every number below n ; Check from right to left ; If number is not prime at any stage ; Check from left to right ; If number is not prime at any stage ; If flag is still true ; Return the required sum ; Driver code
< ? php $ N = 10005 ; $ prime = array_fill ( 0 , $ N , true ) ; function sieve ( ) { global $ prime , $ N ; $ prime [ 1 ] = false ; $ prime [ 0 ] = false ; for ( $ i = 2 ; $ i < $ N ; $ i ++ ) if ( $ prime [ $ i ] ) for ( $ j = $ i * 2 ; $ j < $ N ; $ j += $ i ) $ prime [ $ j ] = false ; } function sumTruncatablePrimes ( $ n ) { global $ prime , $ N ; $ sum = 0 ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) { $ num = $ i ; $ flag = true ; while ( $ num ) { if ( ! $ prime [ $ num ] ) { $ flag = false ; break ; } $ num = ( int ) ( $ num / 10 ) ; } $ num = $ i ; $ power = 10 ; while ( ( int ) ( $ num / $ power ) ) { if ( ! $ prime [ $ num % $ power ] ) { $ flag = false ; break ; } $ power *= 10 ; } if ( $ flag ) $ sum += $ i ; } return $ sum ; } $ n = 25 ; sieve ( ) ; echo sumTruncatablePrimes ( $ n ) ; ? >