export function sieveOfEratosthenes(limit: number): number[] {
if (!Number.isInteger(limit) || limit <= 1) {
throw new Error("limit should be an integer greater than 1");
}
const maybePrime: boolean[] = new Array(limit + 1).fill(true);
for (let i = 2; i * i <= limit; i++) {
if (!maybePrime[i]) continue;
for (let j = i * i; j <= limit; j += i) {
maybePrime[j] = false;
}
}
const primes: number[] = [];
for (let i = 2; i < maybePrime.length; i++) {
if (maybePrime[i]) {
primes.push(i);
}
}
return primes;
}
export function* primeGenerator() {
type NumberGen = Generator<number, void, any>;
function* filter(input: NumberGen, prime: number): NumberGen {
while (true) {
const {done, value} = input.next();
if (done) break;
if (value % prime !== 0) yield value;
}
}
let chain: NumberGen = (function* () {
let i = 2;
while (true) yield i++;
})();
while (true) {
const {done, value} = chain.next();
if (done) break;
yield value;
chain = filter(chain, value);
}
}
export const isPrime = (num: number): boolean => {
if (num <= 0 || !Number.isInteger(num)) {
throw new Error("only natural numbers are supported");
}
if (num === 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
};