ITMISS
2019-07-13 10:04:17
如何找到0到100之間的素?cái)?shù)?在Javascript中,如何找到0到100之間的素?cái)?shù)?我想過(guò)了,我不知道怎么找到他們。我想做x%x,但我發(fā)現(xiàn)了一個(gè)明顯的問(wèn)題。到目前為止,這就是我所擁有的:但不幸的是,這是有史以來(lái)最糟糕的代碼。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貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
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)

瀟瀟雨雨
TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊
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
添加回答
舉報(bào)
0/150
提交
取消