เราต้องเขียนฟังก์ชันที่รับตัวเลข n หาผลรวมของจำนวนเฉพาะทั้งหมดที่น้อยกว่า n
ตัวอย่าง: n=10 → จำนวนเฉพาะ: 2,3,5,7 → ผลรวม = 17
ตัวอย่างโค้ด
const isPrime = (num) => {
let x = Math.floor(Math.sqrt(num));
let j = x;
while (j >= 2) { if (num % j === 0) { return false; } j--; }
return true;
};
const sumOfPrimes = (num = 10) => {
let iter = num, sum = 0;
while (iter >= 2) { if (isPrime(iter)) { sum += iter; } iter--; }
return sum;
};
console.log(sumOfPrimes(14));
console.log(sumOfPrimes(10));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
41 17 1060