2016 Update
This commit is contained in:
parent
948b86eafa
commit
dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions
|
|
@ -0,0 +1,41 @@
|
|||
function primeGenerator(num, showPrimes) {
|
||||
var i,
|
||||
arr = [];
|
||||
|
||||
function isPrime(num) {
|
||||
// try primes <= 16
|
||||
if (num <= 16) return (
|
||||
num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13
|
||||
);
|
||||
// cull multiples of 2, 3, 5 or 7
|
||||
if (num % 2 == 0 || num % 3 == 0 || num % 5 == 0 || num % 7 == 0)
|
||||
return false;
|
||||
// cull square numbers ending in 1, 3, 7 or 9
|
||||
for (var i = 10; i * i <= num; i += 10) {
|
||||
if (num % (i + 1) == 0) return false;
|
||||
if (num % (i + 3) == 0) return false;
|
||||
if (num % (i + 7) == 0) return false;
|
||||
if (num % (i + 9) == 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof num == "number") {
|
||||
for (i = 0; arr.length < num; i++) if (isPrime(i)) arr.push(i);
|
||||
// first x primes
|
||||
if (showPrimes) return arr;
|
||||
// xth prime
|
||||
else return arr.pop();
|
||||
}
|
||||
|
||||
if (Array.isArray(num)) {
|
||||
for (i = num[0]; i <= num[1]; i++) if (isPrime(i)) arr.push(i);
|
||||
// primes between x .. y
|
||||
if (showPrimes) return arr;
|
||||
// number of primes between x .. y
|
||||
else return arr.length;
|
||||
}
|
||||
// throw a default error if nothing returned yet
|
||||
// (surrogate for a quite long and detailed try-catch-block anywhere before)
|
||||
throw("Invalid arguments for primeGenerator()");
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
// first 20 primes
|
||||
console.log(primeGenerator(20, true));
|
||||
|
||||
// primes between 100 and 150
|
||||
console.log(primeGenerator([100, 150], true));
|
||||
|
||||
// numbers of primes between 7700 and 8000
|
||||
console.log(primeGenerator([7700, 8000], false));
|
||||
|
||||
// the 10,000th prime
|
||||
console.log(primeGenerator(10000, false));
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
Array [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 51, 59, 61, 67, 71 ]
|
||||
|
||||
Array [ 101, 103, 107, 109, 113, 127, 131, 137, 139, 149 ]
|
||||
|
||||
30
|
||||
|
||||
104729
|
||||
Loading…
Add table
Add a link
Reference in a new issue