Find the sum of all Truncatable primes below N | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  1000005 NEW_LINE bool prime [ N ] ; void sieve ( ) { memset ( prime , true , sizeof prime ) ; prime [ 1 ] = false ; prime [ 0 ] = false ; for ( int i = 2 ; i < N ; i ++ ) if ( prime [ i ] ) for ( int j = i * 2 ; j < N ; j += i ) prime [ j ] = false ; } int sumTruncatablePrimes ( int n ) { int sum = 0 ; for ( int i = 2 ; i < n ; i ++ ) { int num = i ; bool flag = true ; while ( num ) { if ( ! prime [ num ] ) { flag = false ; break ; } num /= 10 ; } num = i ; int power = 10 ; while ( num / power ) { if ( ! prime [ num % power ] ) { flag = false ; break ; } power *= 10 ; } if ( flag ) sum += i ; } return sum ; } int main ( ) { int n = 25 ; sieve ( ) ; cout << sumTruncatablePrimes ( n ) ; return 0 ; }