如何找到0到100之間的素數(shù)?在Javascript中,如何找到0到100之間的素數(shù)?我想過了,我不知道怎么找到他們。我想做x%x,但我發(fā)現(xiàn)了一個明顯的問題。到目前為止,這就是我所擁有的:但不幸的是,這是有史以來最糟糕的代碼。var prime = function (){var num;for (num = 0; num < 101; num++){
if (num % 2 === 0){
break;
}
else if (num % 3 === 0){
break;
}
else if (num % 4=== 0){
break;
}
else if (num % 5 === 0){
break;
}
else if (num % 6 === 0){
break;
}
else if (num % 7 === 0){
break;
}
else if (num % 8 === 0){
break;
}
else if (num % 9 === 0){
break;
}
else if (num % 10 === 0){
break;
}
else if (num % 11 === 0){
break;
}
else if (num % 12 === 0){
break;
}
else {
return num;
}}};console.log(prime());
3 回答

皈依舞
TA貢獻1851條經(jīng)驗 獲得超3個贊
function getPrimes(max) { var sieve = [], i, j, primes = []; for (i = 2; i <= max; ++i) { if (!sieve[i]) { // i has not been marked -- it is prime primes.push(i); for (j = i << 1; j <= max; j += i) { sieve[j] = true; } } } return primes;}
getPrimes(100)

牧羊人nacy
TA貢獻1862條經(jīng)驗 獲得超7個贊
function isPrime (n){ if (n < 2) return false; /** * An integer is prime if it is not divisible by any prime less than or equal to its square root **/ var q = Math.floor(Math.sqrt(n)); for (var i = 2; i <= q; i++) { if (n % i == 0) { return false; } } return true;}
n
- 3 回答
- 0 關注
- 723 瀏覽
添加回答
舉報
0/150
提交
取消