ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับช่วงอาร์เรย์สองตัวเลข ฟังก์ชันควรคืนค่าจำนวนจำนวนเฉพาะ ที่ผลรวมกำลังสองของหลักตัวเลข (squared sum of digits) สุดท้ายได้ 1
เช่น 23 เป็นจำนวนเฉพาะ และ:
2² + 3² = 13 1² + 3² = 10 1² + 0² = 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
คำอธิบายเพิ่มเติม
นี่คือการหา "happy primes" (จำนวนเฉพาะที่เป็น happy number) Happy number คือเลขที่ซ้ำการบวกกำลังสองหลักได้ 1 โค้ดใช้ String.prototype.reduce hack และ loop detection ด้วย array indexOf