Count all prime numbers in a given range whose sum of digits is also prime | Javascript implementation for the above approach ; Create an array for storing primes ; Create a prefix array that will contain whether sum is prime or not ; Function to find primes in the range and check whether the sum of digits of a prime number is prime or not ; Initialise Prime array arr [ ] ; Since 0 and 1 are not prime numbers we mark them as '0' ; Using Sieve Of Eratosthenes ; if the number is prime ; Mark all the multiples of i starting from square of i with '0' ie . composite ; '0' represents not prime ; Initialise a sum variable as 0 ; Check if the number is prime ; A temporary variable to store the number ; Loop to calculate the sum of digits ; Check if the sum of prime number is prime ; if prime mark 1 ; If not prime mark 0 ; computing prefix array ; Function to count the prime numbers in the range [ L , R ] ; Function Call to find primes ; Prlet the result ; Input range ; Function Call
let maxN = 1000000 ; let arr = Array . from ( { length : 1000001 } , ( _ , i ) => 0 ) ; let prefix = Array . from ( { length : 1000001 } , ( _ , i ) => 0 ) ; function findPrimes ( ) { for ( let i = 1 ; i <= maxN ; i ++ ) arr [ i ] = 1 ; arr [ 0 ] = 0 ; arr [ 1 ] = 0 ; for ( let i = 2 ; i * i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) { for ( let j = i * i ; j <= maxN ; j += i ) { arr [ j ] = 0 ; } } } let sum = 0 ; prefix [ 0 ] = 0 ; for ( let i = 1 ; i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) { let temp = i ; sum = 0 ; while ( temp > 0 ) { let x = temp % 10 ; sum += x ; temp = Math . floor ( temp / 10 ) ; if ( arr [ sum ] == 1 ) { prefix [ i ] = 1 ; } else { prefix [ i ] = 0 ; } } } } for ( let i = 1 ; i <= maxN ; i ++ ) { prefix [ i ] += prefix [ i - 1 ] ; } } function countNumbersInRange ( l , r ) { findPrimes ( ) ; let result = prefix [ r ] - prefix [ l - 1 ] ; document . write ( result + " " ) ; } let l , r ; l = 5 ; r = 20 ; countNumbersInRange ( l , r ) ;