rhai/scripts/primes.rhai

33 lines
747 B
Plaintext
Raw Normal View History

2020-03-16 07:50:12 +01: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();
const MAX_NUMBER_TO_CHECK = 1_000_000; // 9592 primes <= 100000
2020-03-12 16:46:40 +01:00
let prime_mask = [];
prime_mask.pad(MAX_NUMBER_TO_CHECK, true);
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;
for p in range(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
//print(p);
2020-03-12 16:46:40 +01:00
2020-05-03 16:12:10 +02:00
total_primes_found += 1;
for i in range(2 * p, MAX_NUMBER_TO_CHECK, p) {
prime_mask[i] = false;
i += p;
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
if total_primes_found != 78_498 {
print("The answer is WRONG! Should be 78,498!");
2020-05-13 05:56:48 +02:00
}