Skip to content

Instantly share code, notes, and snippets.

@LuoZijun
Last active August 30, 2016 04:09
Show Gist options
  • Save LuoZijun/dc6ad4a6d6e287c11df2962ac83a8eb1 to your computer and use it in GitHub Desktop.
Save LuoZijun/dc6ad4a6d6e287c11df2962ac83a8eb1 to your computer and use it in GitHub Desktop.
JavaScript 寻找素数
"use strict";
function primes_with_generator(start, max){
// start: int ( start >= 2 )
// max : int
if ( start < 2 ) throw new Error("start > 2 | start == 2");
var generator = function* (start, max){
var n = start || 2;
while ( n <= max ){
yield n++;
}
};
var isPrime = function (n){
var _is_prime = true;
for (let i=2; i<=Math.floor(Math.sqrt(n)); i++){
if ( n % i == 0 ){
_is_prime = false;
break;
}
}
return _is_prime;
};
var gen = generator(start, max);
var result = [];
while (true){
let next = gen.next();
if ( next.done ) break;
let is_prime = isPrime(next.value);
if ( is_prime ) result.push(next.value);
}
return result;
}
function primes (n, max){
// n : int ( n >= 2 )
// max: int
if ( n < 2 ) throw new Error("n > 2 | n == 2");
var is_prime = true;
// WARN: RangeError: Maximum call stack size exceeded
for (let i=2; i<=Math.floor(Math.sqrt(n)); i++){
if ( n % i == 0 ){
is_prime = false;
break;
}
}
var result;
if ( n == max ) {
result = is_prime ? [n] : [];
} else {
result = is_prime ? [n].concat(primes(n+1, max)) : primes(n+1, max);
}
return result;
}
function test_primes_with_generator(){
let start = 2;
let max = 100;
let result = primes_with_generator(start, max);
console.log(JSON.stringify(result));
}
function test_primes(){
let start = 2;
let max = 10;
let result = primes(start, max);
console.log(JSON.stringify(result));
}
function test(){
test_primes();
test_primes_with_generator();
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment