需要在JavaScript中生成素数

时间:2014-02-23 08:36:52

标签: javascript jscript

我正在编写一个JavaScript来生成从2到100的素数。但是它不起作用,无法弄明白。

你能帮我吗?

var array = new Array(100);

for (var i=2 ; i<=array.length-1; i++) {
    if((i%2===0) || (i%3===0))
        continue;
    document.writeln(i+",");
}

我修改了我的答案,但现在它没有打印2&amp; 3;我怎么能包括2&amp; 3 ... 结果是:

5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97

19 个答案:

答案 0 :(得分:7)

function isPrime(num) {
    for ( var i = 2; i < num; i++ ) {
        if ( num % i === 0 ) {
            return false;
        }
    }
    return true;
}

function display(n) {
    var arr = [2];
    for ( var i = 3; i < n; i+=2 ) {
        if ( isPrime(i) ) {
            arr.push(i);
        }
    }
    console.log(arr); // use arr result on your own
}

display(100);

注意:显示功能中指定 n 参数,并将素数从2增加到 n ...

查看JSFiddle

更新:请注意,上面的脚本是正确的,我要离开它,但另外添加了一个功能相同的功能:

function prime(n,flag) {
    ( typeof flag === "undefined" || flag === false ) ? flag = false : flag = true;

    function isPrime(num) {
        if ( num === 0 || num === 1 ) {
            return false;
        }
        for ( var i = 2; i < num; i++ ) {
            if ( num % i === 0 ) {
                return false;
            }
        }
        return true;
    }

    if ( flag ) {
        var arr = [2];
        for ( var i = 3; i <= n; i+=2 ) {
            if ( isPrime(i) ) {
                arr.push(i);
            }
        }
        return arr;
    } else {
        return isPrime(n);
    }
}

解释prime函数需要两个参数,第一个是必需的,第二个是可选的。如果仅指定了第一个参数,则函数将返回truefalse基于数字属于或不属于素数。如果第二个参数指定为true(或除undefinedfalse之外的任何其他类型),则函数将返回从array2的素数n }。例如:

console.log(prime(2)); // returns true ( 2 is prime )
console.log(prime(8)); // returns false ( 8 isn't prime )

console.log(prime(100,true)); // returns [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

答案 1 :(得分:3)

使用javascript生成器的版本:

&#13;
&#13;
function* take(length, iterable) {
  for (let x of iterable) {
    if (length <= 0) return;
    length--;
    yield x;
  }
}

function* primes() {
  let n = 2;

  while (true) {
    if (isPrime(n)) yield n;
    n++;
  }

  function isPrime(num) {
    for (var i = 2; i <= Math.sqrt(num); i++) {
      if (num % i === 0) {
        return false;
      }
    }
    return true;
  }
}

console.log([...take(4, primes())]); //[ 2, 3, 5, 7 ]
&#13;
&#13;
&#13;

答案 2 :(得分:3)

var enterNumber = prompt("Enter number: ");

for(var i=1; i<=enterNumber ;i++){

        var isPrime = true;

        for(var j=2; j<i; j++){
            if(i%j === 0){
                isPrime = false;
            }
        }
        if(isPrime === true){
            console.log(i);
        }
    }

答案 3 :(得分:2)

您的原始代码存在许多缺陷。要实现Sieve of Eratosthenes,您需要将找到的每个素数添加到数组中,然后针对您到目前为止找到的每个素数测试下一个候选素数。如果候选者不能被数组中的任何素数整除,那么它就是素数,你可以将它添加到素数数组中。

这是一个工作版本(Demonstration):

function start() {    
    var array = [2, 3];
    for (var i = 5; i <= 100; i += 2) {
        if (array.every(function(p) { return i % p; })) {
            array.push(i);
        }
    }
    var result = array.join(",");
    document.getElementById("output").innerHTML = result;
}
start();

请注意,这取决于ECMAScript 5中引入的Array.prototype.every

答案 4 :(得分:1)

你有很多方法可以实现这一目标。

你基本上是在正确的方式,但是,你必须检查每个数字,如果它可以被你到目前为止确定的每个素数整除:

var primes = [2],isPrime;

for (var i=3;i<100;i+=2){
    isPrime = true;
    // test the number you are examaning against
    // all the primes you found so far
    for (var j = 0;j<primes.length;j++){
        if (i%primes[j]==0){
            isPrime=false;
            break;
        }
    }
    if(isPrime){primes.push(i)}
}
console.log(primes);

See the result here

或者您可以使用Sieve of Eratosthenes对所有数字进行排序,以避免重复测试。

SoE的真正实现:

// initialize the array first
var numbers = [], primes = [], maxNumber = 100;

for(var i = 2;i<=maxNumber;i++){
 numbers.push(i);   
}

while(numbers.length){
    primes.push(numbers.shift());
    numbers = numbers.filter(
        function(i){return i%primes[primes.length-1]!=0}
    );
}

console.log(primes);

Demo

答案 5 :(得分:1)

我们只用一个循环就可以找到直到 n 的素数,而且我将循环增加了 +2:

function primeNumber(n) {
    let arr = [2];
    for (let i = 3; i <= n; i += 2)
        if (!((i % 3 == 0 && i > 3) || (i % 5 == 0 && i > 5) || (i % 7 == 0 && i > 7) || (i % 9 == 0 && i > 9))) {
            arr.push(i);
        }
    return arr;
}
primeNumber(100);
// output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

时间复杂度为 o(n/2);

答案 6 :(得分:1)

这是一个幼稚的功能性答案:

const prime = to => [...Array(to-1).keys()].map(i=>i+2).filter(n =>
  [...Array(n-2).keys()].map(i=>i+2).reduce((acc,x)=> acc && n % x !== 0, true)
)

这将返回一个包含所有素数的数组。

答案 7 :(得分:1)

这可能是一种有效的方式:

function calcPrimes(max){
    var primes = [];
    for(var i=2; i<=max; i++){
        var isPrime = true; 
        for(var j=0; j<primes.length; j++){
            var p = primes[j];
            if( i % p === 0){
                //it is divisible by another prime, so it's not prime
                isPrime=false;
                break;
            }
            //you don't need to check primes bigger than sqrt(i)
            if(p*p > i)
                break;
         }
        if(isPrime)
            primes.push(i);
    }
    console.log(JSON.stringify(primes))
    console.log(primes.length)
}
calcPrimes(100);

答案 8 :(得分:0)

function isPrime(num) {
    if (num % 2 == 0) {
        return false;
    }

    let n = Math.sqrt(num);

    for ( var i = 3; i <= n; i += 2 ) {
        if ( num % i === 0 ) {
            return false;
        }
    }

    return true;
}

function print(n) {
    var arr = [2];
    for ( var i = 3; i < n; i+=2 ) {
        if ( isPrime(i) ) {
            arr.push(i);
        }
    }
    console.log(arr);
}

print(100);

答案 9 :(得分:0)

Please try this,
var a = [...Array(100).keys()];
var primeNumbers = a.map(v => { 
    if (v % 2 === 0 || v % 3 === 0) { 
      if (v === 2 || v === 3) {
       return v;
      } else {
       return;
      } 
    } else {
      return v;
    }
});

primeNumbers.filter(val => val);

you will get 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97

答案 10 :(得分:0)

我知道这个问题是在2014年问到的,但以防万一OP或任何人想知道如何使用Javascript生成小质数的情况,我已经在https://github.com/HMaxF/generate-small-prime-number中共享了小JS代码。

在我的macbook pro中,我可以在25秒左右的时间内生成从2到1亿的所有质数,但是您的计算机结果会有所不同。

答案 11 :(得分:0)

我同意 p.s.w.g 。您的原始代码有很多缺陷。

var prime = [2,3,5,7];

for(var x = 0; x < 100; x++){
    var isPrime = prime.map(n => x%n > 0).filter(t => !t).length <= 0;
    if(isPrime || prime.includes(x)){
        console.log(x);
   }
}

答案 12 :(得分:0)

function printPrimes(num) {
	let sum = []
  for(let i = 2; i<=num; i++) {
		if(check(i)) {
			sum.push(i)
		}
	}
	return sum
}
function check(num) {     // function to check number is prime or not
	if(num <= 1 || typeof num !== 'number') {
		return false
	}else if(num ===2) {
		return true
	}else if (num%2 === 0) {
		return false
	}
	for(let i=3; i*i <= num;i +=2) {
		if(num%i === 0) {
			return false
		}
	}
   return true
}	
console.log(printPrimes(100))

答案 13 :(得分:0)

只需将此Java脚本用于从2到素数的素数:

function primeFactorsTo(num)
{
    var store  = [], i, j, primes = [];
    for (i = 2; i <= num; ++i) 
    {
        if (!store [i]) 
          {
            primes.push(i);
            for (j = i << 1; j <= num; j += i) 
            {
                store[j] = true;
            }
        }
    }
    return primes;
}

console.log(primeFactorsTo(200));

答案 14 :(得分:0)

I’ve Made the easiest Algorithm to solve this Problem

Step 1 –  Create a function to check a number is prime or not  (PrimeFilter) .

Step 2 – Create another function to print prime numbers smaller than given  number ,
               inside it declare an empty array .
Step 3 – Loop from 2 ( first prime number ) to the given number , and pass every loop value
              to the function PrimeFilter ( It will check every loop value if its prime or not ) .
Step 4 – If its a prime add it to the empty array .   Thats it :)


    function PrimeFilter(num){
         if(num===0){
           return false;
        }
        else if(num===1){
            return false;
        }

        else if(num===2){
            return true;
        }

        else {

            for(var i=2; i<num; i++){
                if(num%i===0){
                    return false;
                }
            }
            return true;
         }
     }

     function UptoPrime(number){
        var List =[];
         for(var i=2; i<=number; i++){
            if(PrimeFilter(i)){ 
                List.push(i);
            }
         }
         console.log(List.join(' '));
    }

答案 15 :(得分:0)

与此answer相关,这将检查素数并在给定范围之间打印所需的素数

const isPrime = num => {
  for(let i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}

primes = [] ;

for(let i = 2; i < max ; i ++) {
if(isPrime(i)) {
   primes.push(i)
 }
}

console.log(primes);

答案 16 :(得分:0)

最近使用素数,并已登陆此页面。这是我使用enter link description here算法并进行6k ± 1优化并忽略5的所有偶数和除数的工作解决方案。

将代码复制并粘贴为html。打印约1,000,000中第一个10 seconds质数

<!DOCTYPE html>
<HTML>
<HEAD>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<BODY>
<SCRIPT type="text/javascript">
// The largest integer Java natively supports is 2^53-1, so these
// routines are designed to work for *positive* integers up to that.

// Currently the function check does the idiot proof to see only positive
// integers (not too large) are passed to the other routines.

 
// trial_divide(N,max) uses trial division to seek the smallest
// prime divisor of N, returns 0 if none found.


function trial_divide(N,max) {
  // Trial divides the positive integer N by the primes from 2 to max
  // Returns the first prime divisor found, or 0 if none found
  // Note: if N < max^2 is a prime, then N will be returned. 
  if (N%2 == 0) return 2;
  if (N%3 == 0) return 3;
  // No need to go past the square root of our number
  var Stop = Math.min(Math.sqrt(N),max);
  // Okay, lets "wheel factor" alternately adding 2 and 4
  var di=2;
  for(i=5; i<=Stop; i+=di, di=6-di) {
    if (N%i == 0) return i;
  };
  if (N >= max*max) return 0; 
  return N;
}


// modmult(a,b,N) finds a*b (mod N) where a, b, and N can be 
// up to (2^53-1)/2.  Might up this to 2^53-1 eventually...

  function modadd(a,b,N) {
  // When the integers a, b satisfy a+b > 2^53-1, then (a+b)%N is wrong
  // so we add this routine to allow us to reach a, b = 2^53-1.
    if (a+b > 9007199254740991) {
      // Could reduce a and b (mod N) here, but assuming that has already been done
      // won't hurt if not... subtract 2^52 from one, 2^52-1 from the other and the
      // add it back modulo N (MaxInt+1)  
      var t = ( (a-4503599627370496) + (b-4503599627370495) )%N;
      return ( t + (9007199254740991 % N) );
    }
    // Usual case: a + b is not too large:
    return ( (a+b)%N );
  }

function modmult(a,b,N) {
  if (a > N) a = a%N;
  if (b > N) b = b%N;
  if (a*b <= 9007199254740991) {
    return ((a*b)%N);
  } else {
    if (b > a) return modmult(b,a,N);

    // Right to left binary multiplication
    var t = 0;
    var f = a;
    while (b > 1) {
      if ((b & 1) == 1) t = modadd(t,f,N);
      b = Math.floor(b/2);
      f = modadd(f,f,N);
    };
    t = modadd(t,f,N);
    return t;
  }
}

// modpow(a,exp,N) finds a^exp (mod N) where a, b, and N are 
// limited by modmult

function modpow(a,exp,N) {
  if (exp == 0) return 1;

  // Right to left binary exponentiation
  var t = 1;
  var f = a;
  while (exp > 1) {
    if ((exp & 1) == 1) {  // if exponent is odd
      t = modmult(t,f,N);
    }
    exp = Math.floor(exp/2);
    f = modmult(f,f,N);
  };
  t = modmult(t,f,N);
  return t;
}

// SPRP(N,a) checks if N (odd!) is a strong probable prime base a 
// (returns true or false)

function SPRP(N,a) {
  var d = N-1; s = 1;  			// Assumes N is odd!
  while ( ((d=d/2) & 1) == 0) s++;	// Using d>>1 changed the sign of d!
  // Now N-1 = d*2^s with d odd
  var b = modpow(a,d,N);
  if (b == 1) return true;
  if (b+1 == N) return true;
  while (s-- > 1) {
    b = modmult(b,b,N);
    if (b+1 == N) return true;
  }
  return false;
}

// The idiot proofing, answer returning script

function check(e){
  if (e.hasAttribute("disabled")) return;
  var start = performance.now();
  var TrialLimit = 1300; // Should be bigger, like 10000
  var N = document.getElementById("primenumbercheck").value;
  var Result = "Unknown error";
  var a;
    
  if (N > 9007199254740991) {
    Result = "Sorry, this routine will only handle integers below 9007199254740991.";
  } else if (N == 1) {
    Result = "The number 1 is neither prime or composite (it the multiplicative identity).";
  } else if (N < 1) {
    Result = "We usually restrict the terms prime and composite to positive integers";
  } else if (N != Math.floor(N)) {
    Result = "We usually restrict the terms prime and composite to positive integers";
  } else {
    // Okay, N is of a resonable size, lets trial divide
    window.status = "Trial dividing " + N + " to " + TrialLimit + ".";
    i = trial_divide(N,TrialLimit);
    if (i > 0 && i != N) { 
      Result = N+" is not a prime! It is "+i+" * "+N/i;
    } else if (N < TrialLimit*TrialLimit) {
      Result = N+" is a (proven) prime!";
    } else if ( SPRP(N,a=2) && SPRP(N,a=3) && SPRP(N,a=5) && SPRP(N,a=7) 
    		&& SPRP(N,a=11) && SPRP(N,a=13) && SPRP(N,a=17)) {
      // Some of these tests are unnecessary for small numbers, but for
      // small numbers they are quick anyway.
      if (N < 341550071728321) {
        Result = N + " is a (proven) prime.";
      } else if (N == 341550071728321) {
        Result = N+" is not a prime! It is 10670053 * 32010157.";
      } else {
        Result = N + " is probably a prime (it is a sprp bases 2, 3, 5, 7, 11, 13 and  17).";
      };
    } else {
      Result = N+" is (proven) composite (failed sprp test base "+a+").";
    };
  };
  var end = performance.now();
  var timeTaken = end - start;
  window.status= "Done!"; // here so says done when present alert box
  var x = document.getElementsByClassName("primecheck");
  x[0].innerHTML = Result;
  setTimer(timeTaken);

}

function generate(e){
  if (e.hasAttribute("disabled")) return;
  var start = performance.now();
  var x = document.getElementsByClassName("primelist");
  var N = document.getElementById("primenumberlist").value;

  var i = 2;
  var Result = "2, ";
  var currentInt = 3;
  var possiblePrime;
  if (N == 2) 
    Result = Result + currentInt + ", ";
  else {
    while (i < N) {
      possiblePrime = false;
        if(currentInt == 3) {
          Result = Result + currentInt + ", ";
            possiblePrime = false;
        }
	else if(currentInt % 5 == 0 && currentInt > 5) {
	  possiblePrime = false;
	}
        else if(currentInt % 6 == 1 || currentInt % 6 == 5) 
          possiblePrime = true;
        if(possiblePrime) {
          if(trial_divide(currentInt,Math.ceil(Math.sqrt(currentInt))) == currentInt) {
            Result = Result + currentInt + ", ";
            i++;
          }
        }
        currentInt = currentInt + 2;
      }
    }
  var end = performance.now();
  var timeTaken = end - start;
  x[0].innerHTML = Result.substring(0, Result.length - 2);
  setTimer(timeTaken);
}

function setTimer(timeTaken) {
  var timerElement = document.getElementsByClassName("timeElapsed")[0];
  var timerPreText = "Time Elapsed: ";
  var duration = convertMS(timeTaken);
  timerPreText = timerPreText + duration.day + " days: " + duration.hour + " hours: " + duration.minute + " minutes: " + duration.seconds + " seconds" + ": " + 

duration.milliseconds + " milliseconds";
  timerElement.innerHTML = timerPreText;
}

function isNumberKey(evt)
{
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
     return false;
     return true;
}

function convertMS( milliseconds ) {
    var day, hour, minute, seconds, milliseconds;
    seconds = Math.floor(milliseconds / 1000);
    milliseconds = milliseconds - (seconds * 1000);
    milliseconds = milliseconds.toFixed(2);
    minute = Math.floor(seconds / 60);
    seconds = seconds % 60;
    hour = Math.floor(minute / 60);
    minute = minute % 60;
    day = Math.floor(hour / 24);
    hour = hour % 24;
    return {
        day: day,
        hour: hour,
        minute: minute,
        seconds: seconds,
	milliseconds: milliseconds
    };
}

function checkInput(input, buttonId)
{
    var name = input.value;
    var cansubmit = (name.length > 0);
    if (cansubmit) {
        document.getElementById(buttonId).removeAttribute("disabled");
    } else {
        document.getElementById(buttonId).setAttribute("disabled", null);
    }
};

</SCRIPT>

<article class="message is-success timerDiv" style="visibility: visible;">
  <div class="message-body">
    <p class="timeElapsed">Time elapsed will be shown here!</p>
  </div>
</article>

<article class="message is-primary">
  <div class="message-body">
    <strong class="title">Check prime number</strong>
	<div class="content" style="margin-top: 10px;">
	<div><input id="primenumbercheck" class="input is-rounded" type="text" placeholder="Enter the number you wanna check..." style="max-width: 25%;" 

onkeypress="return isNumberKey(event)" onkeyup="checkInput(this, 'primenumbercheckButton')">
	<a class="button is-link is-rounded" onclick="check(this)" id="primenumbercheckButton" disabled>Check</a></div>
	</div>
  </div>
</article>

<div class="container is-fullhd">
  <div class="notification primecheck">
    Prime check goes here!
  </div>
</div>

<article class="message is-primary">
  <div class="message-body">
    <strong class="title">List prime numbers</strong>
	<div class="content" style="margin-top: 10px;">
	<div><input id="primenumberlist" class="input is-rounded" type="text" placeholder="Enter the number of prime numbers you wanna generate..." style="max-width: 

35%;" onkeypress="return isNumberKey(event)" onkeyup="checkInput(this, 'primenumberlistButton')">
	<a class="button is-link is-rounded" onclick="generate(this)" id="primenumberlistButton" disabled>List</a></div>
	</div>
  </div>
</article>

<div class="container is-fullhd">
  <div class="notification primelist">
    Prime list goes here!
  </div>
</div>

</div>

</BODY>
</HEAD>
</HTML>

答案 17 :(得分:0)

以下是使用Eratosththenes筛选的变体生成无限数量素数的工作示例。这是一个真正的SoE,并不执行试验分裂来确定一个数字是否为素数。它可能看起来有点奇怪,但这是因为它的设计工作没有任何上限。

<input type=button value="Start" onClick="do_cancel(); do_once()">
<input type=button value="Stop" onClick="do_cancel()">
<table id="mytable"></table>

<script>
'use strict';
(function () {
    var ptable = document.getElementById("mytable");
    var prow = [2, 3];
    function insertPrimeIntoTable(prime) {
        prow.push(prime);
        if( prow.length < 10 ) return false;
        var tr = document.createElement('tr');
        for( var i = 0; i < prow.length; ++i ) {
            var cell = document.createElement('td');
            cell.appendChild( document.createTextNode( prow[i] ) );
            tr.appendChild( cell );
        }
        ptable.appendChild( tr );
        prow = [];
        return true;
    };

    var factors = [];
    function insertPrimeIntoSieve( factor ) {
        var where = factor;
        while( factors[where] )
            where += factor;
        /* while( factors.length < where ) factors.push(0); */
        factors[ where ] = factor;
    }

    var primes = [];
    var a_prime = 3, a_squared_prime = 9, maybe_prime = 3;
    var canceller;
    function do_once() {
        var factor = factors[0];
        maybe_prime += 2;
        if( factor ) {
            //if( 0 != (maybe_prime % factor) )
            //  throw "Unexpected remainder.";
            insertPrimeIntoSieve( factor );
        } else if( maybe_prime < a_squared_prime ) {
            insertPrimeIntoTable( maybe_prime );
            primes.push( maybe_prime );
        } else if( maybe_prime == a_squared_prime ) {
            insertPrimeIntoSieve( a_prime );
            a_prime = primes.shift();
            a_squared_prime = a_prime * a_prime;
        } else {
            throw "Critical math failure:  Programmer or compiler is innumerate.";
        }
        factors.shift();
        canceller = window.setTimeout( do_once, 5 );
    };
    function do_cancel() {
        if( canceller ) window.clearTimeout( canceller );
        canceller = null;
    }
    window.do_once = do_once;
    window.do_cancel = do_cancel;
})();
</script>

答案 18 :(得分:0)

前一段时间,我想出了一个带有生成器fn的打字稿类,认为它可能有用。

model = keras.Sequential([
    keras.layers.Dense(32, input_shape=(X.shape[-1],)),
    keras.layers.Dense(1)
])

一个简单的电话就可以得到所有素数

export default class PrimeNumbers {
_number: number
_primes: Array<Buffer> = []

constructor(_number: number) {
    this._number = _number
    var gen = this.generator();
    var curr = gen.next();
    
    while (!curr.done) {
      if(curr.value)
        this._primes.push(Buffer.from(curr.value.toString()))
      curr = gen.next();
    }
}

getPrimes() { 
  return  this._primes 
}

*generator(): IterableIterator<number> {

 /**
 * An integer is prime if it is not divisible by any prime less than or equal to its square root
 **/
  var i = 2;
    if(this._number >= 2 ) {
    
    function isPrime(val: number) {
      for (var i = 2; i <= Math.sqrt(val); i++) {
        if (0 === val % i ) {
          return false;
        }
      }
      return true;
    }

    while(i < this._number) { 
      yield ( isPrime(i))? i: 0 ;
      i++;
    }
    return true;
  }
    return false     
 }



}