functionisPrimeNumber(num) { if (num === 1 || num === 2) { returntrue; } for (let index = 2; index < num - 1; index++) { if (num % index === 0) { returnfalse; } } returntrue; }
functiongetPrimeNumbers(end) { const result = []; for (let index = 2; index <= end; index++) { isPrimeNumber(index) && result.push(index); } return result; } console.time('prime numbers - method #1'); console.log(getPrimeNumbers(1000)); console.timeEnd('prime numbers - method #1
试除法-改进版
注意,Math.sqrt开根号效率低于乘法。
1 2 3 4 5 6 7 8 9 10 11 12
functionisPrimeNumber(num) { if (num === 2) { returntrue; } for (let index = 2; index * index <= num; index++) { if (num % index === 0) { returnfalse; } } returntrue; }