简体   繁体   中英

I don't get squaring loop index in prime number function

Below are my functions that sum up all prime numbers that are below a given maxNum .

I don't understand why the for loop in the isPrime function doesn't work when using j <= num instead of j ** 2 <= num .

 function sumPrimes(maxNum) { let sum = 0; for (let i = 2; i <= maxNum; i++) { if (isPrime(i)) { sum += i } } return sum } function isPrime(num) { for (let j = 2; j <= num; j++) { // when I use j ** 2 <= num it works if (num % j === 0) { return false } } return true } console.log(sumPrimes(20))

if you use j <= num , the loop will count j up to the number itself and then it would match num % j === 0 and return false.

So if num was 17, the loop would be executed with 17 <= 17 which passes and the loop body executes 17 % 17 === 0 so it always returns false, no matter what number you pass in.

you could use j < num instead of j <= num in the loop head which should also work because the number itself is never reached when using the smaller than sign.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM