编写一个函数,以正整数为参数,并显示小于或等于它的所有素数之和。
// 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