Find the sum of all Truncatable primes below N | Javascript 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
let N = 1000005 ; let prime = new Array ( N ) ; function sieve ( ) { for ( let i = 0 ; i < prime . length ; i ++ ) { prime [ i ] = true ; } prime [ 1 ] = false ; prime [ 0 ] = false ; for ( let i = 2 ; i < N ; i ++ ) { if ( prime [ i ] ) { for ( let j = i * 2 ; j < N ; j += i ) { prime [ j ] = false ; } } } } function sumTruncatablePrimes ( n ) { let sum = 0 ; for ( let i = 2 ; i < n ; i ++ ) { let num = i ; let flag = true ; while ( num > 0 ) { if ( ! prime [ num ] ) { flag = false ; break ; } num = Math . floor ( num / 10 ) ; } num = i ; let power = 10 ; while ( num / power > 0 ) { if ( ! prime [ num % power ] ) { flag = false ; break ; } power *= 10 ; } if ( flag ) { sum += i ; } } return sum ; } let n = 25 ; sieve ( ) ; document . write ( sumTruncatablePrimes ( n ) ) ;