质数 JavaScript

2022-01-17 00:00:00 numbers javascript

有人可以指导我在这里获取质数吗?这是家庭作业,所以我不想要答案,但我们将不胜感激.真的很烦我:(

Can someone please give me guidance on getting the primenumbers here? This is homework so I don't want the answer but some pointers would be greatly appreciated. It's really annoying me :(

我想我已经接近了.但我遇到的这个问题是数字 25 和 35.这些不是素数,但这个函数正在返回它们

I think I'm close. But this problems I have are number 25 and 35. These are not prime but this function is returning them

var getPrimeNumber = function(n) {
    if(n === 1) return "";
    else if(n == 2) return 2;
    else if(n == 3) return 3;
    else { 
        for(i=Math.floor(Math.sqrt(n)); i>=2; i--){
            //console.log(i);//maybe another var in here? 
            if(n%i !==0 && n%2 !==0 && n%3 !== 0)
                return n; // 25/Math.sqrt(25) will be equal to zero this is what gives me 25 !!!   
        } 
    }
};

推荐答案

基于本页,这将是一种确定数字是否为素数的方法:

Based on this page, this would be a method for determining if a number is a prime number:

function isPrime(number) {
    let start = 2;
    const limit = Math.sqrt(number);
    while (start <= limit) {
        if (number % start++ < 1) return false;
    }
    return number > 1;
}

node.js 中,确定 2 到 100.000 之间的质数大约需要 250 毫秒.

In node.js it takes about 250Ms for determining the prime numbers between 2 and 100.000.

另见...

[编辑八月.2021] 一个更有效的函数.查看这个 Stackblitz 项目

[edit aug. 2021] A somewhat more efficient function. See this Stackblitz project

document.querySelector(`pre`).textContent = `Prime numbers < 100
` +
  [...Array(100)]
  .map((v, i) => isPrime(i) ? i : 0)
  .filter(v => v > 0)
  .join(`
`);

function isPrime(number) {
  const checkPrime = (nr, limit) => {
    for (let start = 3; start <= limit; start += 2) {
      if (0 === nr % start) {
        return false;
      }
    }

    return nr > 1;
  };

  return number === 2 || number % 2 !== 0 && checkPrime(number, Math.sqrt(number));
}

<pre></pre>

相关文章