Counting prime numbers that reduce to 1 within a range using JavaScript


Problem

We are required to write a JavaScript function that takes in a range array of two numbers. Our function should return the count of such prime numbers whose squared sum of digits eventually yields 1.

For instance, 23 is a prime number and,

22 + 32 = 13
12 + 32 = 10
12 + 02 = 1

Hence, 23 should be a valid number.

Example

Following is the code −

 Live Demo

const range = [2, 212];
String.prototype.reduce = Array.prototype.reduce;
const isPrime = (n) => {
   if ( n<2 ) return false;
   if ( n%2===0 ) return n===2;
   if ( n%3===0 ) return n===3;
   for ( let i=5; i*i<=n; i+=4 ) {
      if ( n%i===0 ) return false;
         i+=2;
      if ( n%i===0 ) return false;
   }
   return true;
}
const desiredSeq = (n) => {
   let t=[n];
   while ( t.indexOf(n)===t.length-1 && n!==1 )
   t.push(n=Number(String(n).reduce( (acc,v) => acc+v*v, 0 )));
   return n===1;
}
const countDesiredPrimes = ([a, b]) => {
   let res=0;
   for ( ; a<b; a++ )
      if ( isPrime(a) && desiredSeq(a) )
      res++;
   return res;
}
console.log(countDesiredPrimes(range));

Output

12

Updated on: 20-Apr-2021

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements