Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript를 사용하여 범위 내에서 1로 감소하는 소수 계산

<시간/>

문제

두 숫자의 범위 배열을 받는 JavaScript 함수를 작성해야 합니다. 우리 함수는 자릿수의 제곱합이 결국 1이 되는 소수의 개수를 반환해야 합니다.

예를 들어, 23은 소수이고,

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

따라서 23은 유효한 숫자여야 합니다.

예시

다음은 코드입니다 -

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));

출력

12