輸出0-limit之間所有的素數
阿新 • • 發佈:2019-01-11
function primeNum(limit) { var newArr = []; if (limit == 0 || limit == 1) { newArr = []; } else if (limit == 2) { newArr = [2]; } else if (limit == 3 || limit == 4) { newArr = [2, 3] } else { newArr.push(2, 3); for (var i = 5; i < limit; i++) { if (isPrime(i)) { newArr.push(i); } } } function isPrime(num) { for (var i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) { return false; } } return true; } return newArr; } var prime = primeNum(100); console.log('prime', prime);