简体   繁体   English

质数 JavaScript

[英]Prime 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 :(这真的让我很烦:(

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但是我遇到的这个问题是数字 25 和 35。这些不是素数,但这个函数正在返回它们

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;
}

In node.js it takes about 250Ms for determining the prime numbers between 2 and 100.000.node.js中,确定 2 到 100.000 之间的质数大约需要 250 毫秒。

See also ... 也可以看看 ...

[ edit aug. [编辑八月。 2021 ] A somewhat more efficient function. 2021 ] 一个更有效的功能。 See this Stackblitz project看到这个 Stackblitz 项目

 document.querySelector(`pre`).textContent = `Prime numbers < 100\n` + [...Array(100)] .map((v, i) => isPrime(i) ? i : 0) .filter(v => v > 0) .join(`\n`); 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>

Here's the fastest way to calculate primes in JavaScript, based on the previous prime value.这是在 JavaScript 中根据先前的素数计算素数的最快方法。

function nextPrime(value) {
    if (value > 2) {
        var i, q;
        do {
             i = 3;
             value += 2;
             q = Math.floor(Math.sqrt(value));
             while (i <= q && value % i) {
                 i += 2;
             }
        } while (i <= q);
        return value;
    }
    return value === 2 ? 3 : 2;
}

Test测试

var value, result = [];
for (var i = 0; i < 10; i++) {
    value = nextPrime(value);
    result.push(value);
}
console.log("Primes:", result);

Output输出

Primes: [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]

It is very fast, because:它非常快,因为:

  • It aligns the loop limit to an integer;它将循环限制对齐为整数;
  • It uses a shorter iteration loop, skipping even numbers.它使用较短的迭代循环,跳过偶数。

It can give you the first 100,000 primes in about 130ms, or the first 1m primes in about 4 seconds.它可以在大约 130 毫秒内为您提供前 100,000 个素数,或在大约 4 秒内为您提供前 1m 个素数。

2021 Update 2021 更新

In this day and age, we should be using ES6 generators for this:在这个时代,我们应该为此使用ES6 生成器

// generates "n" primes that follow "startPrime";
function* nextPrimes(startPrime, n) {
    let value = startPrime, i = 0;
    while (i++ < n) {
        if (value > 2) {
            let k, q;
            do {
                k = 3;
                value += 2;
                q = Math.floor(Math.sqrt(value));
                while (k <= q && value % k) {
                    k += 2;
                }
            } while (k <= q);
        } else {
            value = value === 2 ? 3 : 2;
        }
        yield value;
    }
}

test:测试:

const result = [...nextPrimes(1, 10)];
//=> [2,  3,  5,  7, 11, 13, 17, 19, 23, 29]

 function* nextPrimes(startPrime, n) { let value = startPrime, i = 0; while (i++ < n) { if (value > 2) { let k, q; do { k = 3; value += 2; q = Math.floor(Math.sqrt(value)); while (k <= q && value % k) { k += 2; } } while (k <= q); } else { value = value === 2 ? 3 : 2; } yield value; } } const result = [...nextPrimes(1, 10)]; display('Primes: ' + result.join(', ')); function display(msg) { document.body.insertAdjacentHTML( 'beforeend', '<p>' + msg + '</p>' ); }

There is a function that will return true if the number is prime and false if it is not:如果数字是素数,则有一个函数将返回 true,如果不是,则返回 false:

function isPrime(x){     
      d = x-1;
      while (d > 1){
        if ((x % d) == 0) return false;
        d--;
      }
      return true;
    }

Checkout the demo: http://jsbin.com/velapabedi/1/查看演示:http: //jsbin.com/velapabedi/1/

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> <script> function isPrime(x){ d = x-1; while (d > 1){ if ((x % d) == 0) return false; d--; } return true; } if (isPrime(41)){ alert('Prime'); } else{ alert('Not Prime'); } </script> </head> <body> </body> </html>

Here's a simple "sieve" for prime numbers, which can be easily understood, and although it is a naive approach (as opposed to sophisticated efficient prime number tests such as the AKS test ), it is pretty fast (10000 numbers tested in < 1 sec).这是一个简单的素数“筛子”,很容易理解,虽然它是一种幼稚的方法(与复杂的高效素数测试如AKS 测试相反),但它非常快(在 < 1 中测试了 10000 个数字秒)。 It stores the found prime numbers in the array prim[] and tests by using the modulo function ( % ):它将找到的素数存储在数组prim[]中,并使用模函数 ( % ) 进行测试:

The loop tests against already found prime numbers and exits if it is no prime number, ie if the modulo result is 0 (regard the expression i % prim[j])===0 ).循环测试已经找到的素数,如果它不是素数则退出,模结果是否为 0 (关于表达式i % prim[j])===0 )。 Otherwise, it adds it to the list of found prime numbers.否则,它将它添加到找到的素数列表中。

Note that because the only even prime number is 2, the loop step is 2 rather then 1, because from 3 onwards there can't be any further even prime numbers.请注意,因为唯一的偶素数是 2,所以循环步骤是 2而不是 1,因为从 3 开始就不能再有更多的偶素数了。

 var MaxNum = 10000; var prim; function Main() { MaxNum = GetMaxNum(); prim = CalculatePrimes(MaxNum); CheckSome(); } function CalculatePrimes(pMaxNum) { Console.WriteLine("Calculating until " + pMaxNum + "..."); var _prim = [2]; if (pMaxNum > 2) { for (var i = 3; i < pMaxNum; i += 2) { var is_prim = true; if (_prim.length > 0) { for (var j = 0; j < _prim.length; j++) { if ((i % _prim[j]) === 0) { is_prim = false; break; } } } if (is_prim) { _prim.push(i); } } } Console.WriteLine("Prime numbers:"); for (var i = 0; i < _prim.length; i++) { Console.Write(_prim[i] + " "); } Console.WriteLine(); Console.WriteLine("Found " + _prim.length + " prime numbers."); Console.WriteLine(); return _prim; } // test some individual pre-calculated numbers function CheckSome() { var num1 = prim[prim.length - 1]; var num2 = num1 - 1; Console.WriteLine("Test: " + num1.toString() + ". Is it a prime number? " + Is_prime(num1)); Console.WriteLine("Test: " + num2.toString() + ". Is it a prime number? " + Is_prime(num2)); } function Is_prime(n) { if (n > MaxNum) throw "ERROR: n must be <" + MaxNum + "!"; if (prim.indexOf(n) === -1) return false; else return true; }; // ------------ HELPERS to display on screen ------------ var Console = { Section: 1, SectionId: "#section1", NewSection: function() { var $currentSection = $(this.SectionId); this.Section++; this.SectionId = "#section" + this.Section.toString(); $currentSection.before('<div id="section' + this.Section.toString() + '"></div>'); }, Write: function(str) { $(this.SectionId).append(str); }, WriteLine: function(str) { if (str !== undefined && str !== null && str !== "") this.Write(str); this.Write("<br/>"); } }; var GetMaxNum = function() { var result = $("#MaxNumSelect option:selected").val(); return result; } $(document).ready(function() { $("#MaxNumSelect").change(function() { MaxNum = GetMaxNum(); Console.NewSection(); Main(); Console.WriteLine("---------------------------------"); }); Main(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Select max number:&nbsp; <select id="MaxNumSelect"> <option value="10000" default="default">10000</option> <option value="100">100</option> <option value="1000">1000</option> <option value="100000">100000</option> </select> </div> <div id="results"> <div id="section1"></div> </div>

In the above example, we have tested the first 10000 natural numbers.在上面的例子中,我们测试了前 10000 个自然数。 To decide if a given number is a prime number, you simply check if it is contained in the array prim :要确定给定数字是否为质数,您只需检查它是否包含在数组prim中:

function Is_prime(n) {
    if (n>MaxNum) throw "ERROR: n must be <"+CalcToNum+"!";
    if (prim.indexOf(n)===-1)
      return false;
    else
      return true;
};

Of course, in order for this to work the prime numbers need to be pre-calculated.当然,为了使它起作用,需要预先计算素数。

Example: alert(Is_prime(25));示例: alert(Is_prime(25)); - returns false, because 25 is no prime number. - 返回 false,因为 25 不是素数。

Note: The number range must be checked, because the function Is_prime can decide only for numbers which are previously tested by the sieve above.注意:必须检查数字范围,因为函数Is_prime只能决定先前由上述筛子测试过的数字。 If the array is too small for the number to check (ie if not enough prime numbers are pre-calculated), an error is thrown.如果数组太小而无法检查数字(即,如果没有预先计算足够的素数),则会引发错误。

I considered the following in my implementation: Prime numbers are "natural numbers" and it is possible for negative values to be prime numbers .我在实现中考虑了以下内容:素数是“自然数” ,负值可能是素数 This is a more definitive solution with input sanitation:这是一个更明确的输入卫生解决方案:

 function isPrime(num) { //check if value is a natural numbers (integer) //without this check, it returns true if (isNaN(num) || num % 1 !== 0) { return false; } num = Math.abs(num); //*negative values can be primes if (num === 0 || num === 1) { return false; } var maxFactorNum = Math.sqrt(num); for (var i = 2; i <= maxFactorNum; i++) { if (num % i === 0) { return false; } } return true; } //this method in action for (var i = 1; i <= 40; i++) { console.log(i + (isPrime(i) ? ", isPrime" : "")); } //checking anomalies console.log(isPrime(1.22)); console.log(isPrime(1.44)); console.log(isPrime("string"));

I hope my answer proves to be more readable code that also uses best practices.我希望我的答案被证明是更易读的代码,也使用了最佳实践。 For example, some answers leave the square root calculation in the loop causing the method to run that calculation on every loop.例如,一些答案将平方根计算留在循环中,导致该方法在每个循环上运行该计算。

You should return a bool value and new function can be:您应该返回一个bool值,新函数可以是:

function(n) {
    if(n === 1) { return false;}
    else if(n == 2) { return true;}
    else if(n == 3) { return true;}
    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 false;} 
        } 
        }
    return true;
};

In the OP, the control if(n%i !==0 && n%2 !==0 && n%3 !== 0) {return n;} was problematic because even if only single i satisfies this condition, the function returns the number as prime.在 OP 中,控制if(n%i !==0 && n%2 !==0 && n%3 !== 0) {return n;}是有问题的,因为即使只有单个i满足此条件,函数将数字作为素数返回。

In your if statement you got在你的 if 语句中,你得到了

if(n%i !==0 && n%2 !==0 && n%3 !== 0)

you for loop is going till i >= 2, so the n%2 !== 0 is useless, when i = 2, your if would look like:你的 for 循环一直持续到 i >= 2,所以 n%2 !== 0 是没用的,当 i = 2 时,你的 if 看起来像:

if(n%2 !==0 && n%2 !==0 && n%3 !== 0)

Thats 2x the same check, the same is for n%3, its already checked :).那是相同检查的 2 倍,对于 n%3 也是如此,它已经检查过:)。

you should keep a bool to check the n%i !== 0, if it never reach this it's a prime.您应该保留一个布尔值来检查 n%i !== 0,如果它从未达到此值,则它是一个素数。

Good luck with your homework :).祝你功课好运:)。

This is my Answer这是我的答案

 var isPrime = function (n) { if (n < 2) { return false; } else if (n === 2) { return true; } for (var i = 2; i < n; i++) { if (n%i === 0) { return false; } else if (i === n-1) { return true; } } } console.log(isPrime(7));

function isPrime(number) {

  // Immediate exit cases
  switch(true){
    case (number < 2):
      return console.log("Please enter a number greater than or equal to 2.")
    case (number === 2 || number === 3):
      return console.log(number + " is a prime number!")
  }

  // Process number if it does not meet above requirements
  var num = Math.floor(Math.sqrt(number))

  for(var i = 2; i <= num; i++) {
    if(number % i === 0)
      return console.log(number + " is not a prime number")
    else
      return console.log(number + " is a prime number!")
  } 
}

isPrime(27) // 27 is a prime number!
isPrime(30) // 30 is not a prime number
isPrime(55) // 55 is a prime number!
isPrime(2)  // 2 is a prime number!

Try the below code.试试下面的代码。 It checks if the number is prime and if it isn't it logs the number's lowest divisor.它检查数字是否为素数,如果不是,则记录该数字的最低除数。 It is accurate for numbers with less than 17 digits (this theoretically would work for any number but the way JavaScript works means that this isn't true).它对于少于 17的数字是准确的(理论上这适用于任何数字,但 JavaScript 的工作方式意味着这不是真的)。 You can try it out embedded into a website here: https://prime-number-checker-git-main.matt-destroyer.vercel.app/ Or in the snippet below.您可以在此处尝试将其嵌入到网站中: https ://prime-number-checker-git-main.matt-destroyer.vercel.app/ 或在下面的代码段中。

 function check() { function checkIfPrime(number) { if (number < 1) { i = 'less than zero or the number you entered was zero'; return false; } else if (number < 2) { i = 'itself only'; return false; } else if (number % 2 === 0) { i = 2; return false; } else if (number < 10) { if (number === 3) { return true; } else if (number === 5) { return true; } else if (number === 7) { return true; }else if (number === 9) { i = 3; return false; } } else if (number % 3 === 0) { i = 3; return false; } else if (number % 5 === 0) { i = 5; return false; } else if (number % 7 === 0) { i = 7; return false; } else { i = 4; while (i * i < number) { if (number % i === 0) { return false; } i += 2; } return true; } } let i = 0; let input = parseInt(prompt('Enter a number to check if it is prime:')); if (input < 0) { alert(input + ' is not a prime number. A prime number must be a positive integer.'); } else if (input === "") { alert("You cannot check if 'BLANK' is prime."); } else if (input != Math.round(input)) { alert(input + ' is not a prime number. A prime number cannot be a decimal.'); } else { let check = checkIfPrime(input); if (check === true) { alert(input + ' is a prime number.'); } else { alert(input + ' is not a prime number. Its lowest divisor is ' + i + '.'); } } } check();

I barely understand people's code, so here is mine (idk if they are not too clean but i think it's very easy to understand)我几乎看不懂人们的代码,所以这是我的(如果他们不太干净,我认为这很容易理解)

    function primeNum (x){
    const primeArray =[];

    for (var i = 1 ; i <= x ; i++){
        if (x % i === 0){
            primeArray.push(i)
        }
    }

    if (primeArray.length === 2){
        return "it's a prime boys"
    } else {
        return "it's not a prime sorry to say"
    }
}

the concept is simple, prime number is a number that only can divied by only 2 numbers and has modulo equal to 0 ( x % i === 0 ).这个概念很简单,素数是一个只能被 2 个数字整除的数字,并且模等于 0 ( x % i === 0 )。 So if the primeArray has length more than 2 (more than 2 numbers), it's not a prime number.因此,如果primeArray的长度超过 2(超过 2 个数字),则它不是素数。

i don't know what people says about my code, i need your advice guys.我不知道人们对我的代码有什么看法,我需要你们的建议。 Best Regards.此致。

Do you want to know how to determine a number is prime or composite.你想知道如何判断一个数是素数还是合数。 This code make you understand easily.这段代码让你很容易理解。 Input from a number 2.从数字 2 输入。

var p = prompt("Insert a number for check","");
var x = " is a prime number";
for(i=2; i<p; i++){
    if(p%i === 0){
        x = " is a composite number";
        break;
    }
}
alert(p+x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM