33 lines
883 B
JavaScript
33 lines
883 B
JavaScript
|
// prime.js
|
||
|
|
||
|
// Pure ECMAScript version of low level helper
|
||
|
function primeCheckECMAScript(val, limit) {
|
||
|
for (var i = 2; i <= limit; i++) {
|
||
|
if ((val % i) == 0) { return false; }
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
// Select available helper at load time
|
||
|
var primeCheckHelper = (this.primeCheckNative || primeCheckECMAScript);
|
||
|
|
||
|
// Check 'val' for primality
|
||
|
function primeCheck(val) {
|
||
|
if (val == 1 || val == 2) { return true; }
|
||
|
var limit = Math.ceil(Math.sqrt(val));
|
||
|
while (limit * limit < val) { limit += 1; }
|
||
|
return primeCheckHelper(val, limit);
|
||
|
}
|
||
|
|
||
|
// Find primes below one million ending in '9999'.
|
||
|
function primeTest() {
|
||
|
var res = [];
|
||
|
|
||
|
print('Have native helper: ' + (primeCheckHelper !== primeCheckECMAScript));
|
||
|
for (var i = 1; i < 1000000; i++) {
|
||
|
if (primeCheck(i) && (i % 10000) == 9999) { res.push(i); }
|
||
|
}
|
||
|
print(res.join(' '));
|
||
|
}
|
||
|
|