Find the sum of all Truncatable primes below N | Java 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
import java . util . * ; class GFG { static final int N = 1000005 ; static boolean prime [ ] = new boolean [ N ] ; static void sieve ( ) { Arrays . fill ( prime , true ) ; 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 ; } } } } static int sumTruncatablePrimes ( int n ) { int sum = 0 ; for ( int i = 2 ; i < n ; i ++ ) { int num = i ; boolean flag = true ; while ( num > 0 ) { if ( ! prime [ num ] ) { flag = false ; break ; } num /= 10 ; } num = i ; int power = 10 ; while ( num / power > 0 ) { if ( ! prime [ num % power ] ) { flag = false ; break ; } power *= 10 ; } if ( flag ) { sum += i ; } } return sum ; } public static void main ( String [ ] args ) { int n = 25 ; sieve ( ) ; System . out . println ( sumTruncatablePrimes ( n ) ) ; } }