2022-07-24 17:03:35 +02:00
|
|
|
//! This script uses the Sieve of Eratosthenes to calculate prime numbers.
|
2020-03-12 16:46:40 +01:00
|
|
|
|
2020-04-11 10:06:57 +02:00
|
|
|
let now = timestamp();
|
|
|
|
|
2022-09-03 09:48:00 +02:00
|
|
|
const ANSWER = 78_498;
|
|
|
|
const MAX_NUMBER_TO_CHECK = 1_000_000;
|
2020-03-12 16:46:40 +01:00
|
|
|
|
|
|
|
let prime_mask = [];
|
2021-12-15 05:06:17 +01:00
|
|
|
prime_mask.pad(MAX_NUMBER_TO_CHECK + 1, true);
|
2020-03-12 16:46:40 +01:00
|
|
|
|
2020-04-22 13:28:08 +02:00
|
|
|
prime_mask[0] = false;
|
|
|
|
prime_mask[1] = false;
|
2020-03-12 16:46:40 +01:00
|
|
|
|
|
|
|
let total_primes_found = 0;
|
|
|
|
|
2021-12-15 05:06:17 +01:00
|
|
|
for p in 2..=MAX_NUMBER_TO_CHECK {
|
2020-05-03 16:12:10 +02:00
|
|
|
if !prime_mask[p] { continue; }
|
2020-03-12 16:46:40 +01:00
|
|
|
|
2020-05-31 09:57:53 +02:00
|
|
|
//print(p);
|
2020-03-12 16:46:40 +01:00
|
|
|
|
2020-05-03 16:12:10 +02:00
|
|
|
total_primes_found += 1;
|
|
|
|
|
2021-12-15 05:06:17 +01:00
|
|
|
for i in range(2 * p, MAX_NUMBER_TO_CHECK + 1, p) {
|
2020-05-03 16:12:10 +02:00
|
|
|
prime_mask[i] = false;
|
2020-03-12 16:46:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-04 17:22:45 +02:00
|
|
|
print(`Total ${total_primes_found} primes <= ${MAX_NUMBER_TO_CHECK}`);
|
|
|
|
print(`Run time = ${now.elapsed} seconds.`);
|
2020-05-13 05:56:48 +02:00
|
|
|
|
2022-09-03 09:48:00 +02:00
|
|
|
if total_primes_found != ANSWER {
|
|
|
|
print(`The answer is WRONG! Should be ${ANSWER}!`);
|
2021-04-09 16:48:47 +02:00
|
|
|
}
|