-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprime_numbers.html
42 lines (34 loc) · 1.02 KB
/
prime_numbers.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<script>
let primes = [2];
function isPrime(n) {
for (let i = 0; i < primes.length; i++) {
if (n % primes[i] === 0) return false;
}
let lastCalculatedPrime = primes[primes.length - 1];
for (let i = lastCalculatedPrime; i < n; i++) {
if (n % i === 0) return false;
}
return true;
}
function findPrimes(max) {
let lastCalculatedPrime = primes[primes.length - 1];
// Already have cached results
if (lastCalculatedPrime > max) {
let end = primes.findIndex((i) => i > max);
console.log('return fully cached result for max === ' + max);
return primes.slice(0, end);
}
console.log('start calculating primes starting from ' + lastCalculatedPrime);
for (let i = lastCalculatedPrime; i <= max; ++i) {
if (isPrime(i)) {
primes.push(i);
}
}
return primes;
}
console.log(findPrimes(200));
console.log(findPrimes(12));
console.log(findPrimes(120));
console.log(findPrimes(300));
console.log(findPrimes(5000));
</script>