寫一個函數,以正整數為參數,並顯示小於或等於它的所有質數之和。
// Define a function named addPrimeSum that takes a single parameter 'number' function addPrimeSum(number) { // Initialize a variable 'result' to store the sum of prime numbers, starting from 0 let result = 0; // Define an inner function named isPrime that takes a single parameter 'num' function isPrime(num) { // If 'num' is less than 2, it is not prime, so return nothing (undefined) if (num 1) { // Check if 'number' is prime using the isPrime function if (isPrime(number)) { // If it is prime, add it to 'result' result = number; } // Decrement 'number' by 1 to check the next lower number number--; } // Return the total sum of all prime numbers found return result; } console.log(addPrimeSum(5)); console.log(addPrimeSum(21)); console.log(addPrimeSum(100)); console.log(addPrimeSum(239)); console.log(addPrimeSum(956));
> 10 > 77 > 1060 > 5589 > 70241
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3