简体   繁体   中英

Javascript: find first n prime numbers

function primeNumbers(n) {
    array = [];
    for (var i = 2; array.length < n; i++) {
        for (var count = 2; count < i; count++) {
            var divisorFound = false;
            if (i % count === 0) {
                divisorFound = true;
                break;
            }
        }
        if (divisorFound == false) {array.push[i];}
    }
    return array;
}

When I run this code, it seems to get stuck in an infinite loop and doesn't return anything... why?

Try putting this line before your second loop:

var divisorFound = false;

So that this line can access it:

if (divisorFound == false) {array.push(i);}

Take note of the FIXED array.push(i) as NPE said. :)

You may want to read about Variable Scope in JavaScript.

In your code, array.push[i] (with square brackets) doesn't do what you'd like it to. It leaves the array unchanged and returns undefined .

You meant array.push(i) (with parentheses).

This isn't the most advanced way to do this. Using a sieve would be better. However, this is fairly decent and provides a good starting point for approaching prime number code challenges.

/*
 * Get the first n prime numbers
 *
 * @param n Number (integer)
 * @return Array
 *
 */
function getNprimes(n){
  const arr = [];
  let i = 2

  while (arr.length < n) {
    if (isPrime(i)) {
      arr.push(i)
    }
    i++
  } 
  return arr;

  /*
  * @param n (integer)
  * @return Boolean
  *
  */
  function isPrime(n) {

    if ( n < 2 ) {
      return false
    }

    for ( let i = 2; i <= Math.sqrt(n); i++ ) {
      if ( n % i === 0 ) {
          return false;
      } 
    }
    return true
  }

}

此外,您永远不会为array定义长度,因此 for 循环无法知道何时停止。

Actually to find n prime numbers its a lot more optimized [o(n*sqrt(m))] if you just check its sqrt(n). If it is not divisible by square root of n, it is not also divisible by n. here is an example:

 (function(n){ var primes=[]; for (var i=1;i<n;i++){ var prime=true; var rootI=Math.sqrt(i)+1; for (var j=2;j<rootI;j++){ if (i%j==0) {prime=false;break;} }; if (prime) primes.push(i); } document.write(primes.join('-')); })(100000)

The imana97 answare is not correct, because "1" is not prime, while "2" is it. Also they are not the first n numbers but the prime numers smaller than n.

So, my corrected version is:

 (function(n){ var primes=[2]; for (var i=2;primes.length<n;i++){ var prime=true; var rootI=Math.sqrt(i)+1; for (var j=2;j<rootI;j++){ if (i%j==0) {prime=false;break;} }; if (prime) primes.push(i); } document.write(primes.join('-')); })(10000)

<script>
    // first n prime numbers
   function checkPrime(number){
        let temp=2;
        while(temp<number){
          if(number%temp == 0){
              return false;
          }
          temp++;
        } 
     return true;
   }
   function firstnPrime(number){
        var count=0;
    for(var i=2;i<=number;i++){
         if(checkPrime(i)){
             count++;
         }
    }
        return count;
   }


   console.log(firstnPrime(100));

    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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