Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions Maths/Prime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const assert = (condition: boolean, message: string) => {
if (!condition) throw Error(message);
};

/**
* https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
* @param limit An integer _n_ > 1
* @returns All prime numbers from 2 through {@linkcode limit}
*/
export function sieveOfEratosthenes(limit: number): number[] {
assert(limit > 1, "limit should be an integer greater than 1");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Replace all of this - including the assert def. - with if (!Number.isInteger(limit) || limit <= 1) throw new Error("limit should be an integer greater than 1");.

assert(Number.isInteger(limit), "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;
}
}

return maybePrime
.reduce(
(primes, isPrime, number) => (isPrime ? [...primes, number] : primes),

@appgurueu appgurueu Oct 11, 2022

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems horribly inefficient (and also unreadable) to me: It always copies the entire primes array so far just to append a single value. This implies quadratic runtime in the number of primes. Please write it out imperatively:

const primes = [];
for (let i = 2; i < primes.length; i++) if (maybePrime[i]) primes.push(i);

which seems more concise, performant, and readable to me.

@zFl4wless zFl4wless Jul 9, 2023

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm currently finishing this PR. There is a little spelling mistake in your suggestion. In the condition of the for-loop you typed primes instead of maybePrime :)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm currently finishing this PR. There is a little spelling mistake in your suggestion. In the condition of the for-loop you typed primes instead of maybePrime :)

Indeed, that ought to be maybePrime.

[] as number[]
)
.slice(2);
}

/**
* Generator that yields primes.
*
* Inspired by https://gist.github.com/e-nikolov/cd94db0de2a6b70da144124ae93a6458
*/
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);
}
}
35 changes: 35 additions & 0 deletions Maths/test/Prime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { primeGenerator, sieveOfEratosthenes } from "../Prime";

describe(sieveOfEratosthenes, () => {
test.each([-1, 0, 1, 2.123, 1337.80085])(
"should throw an error when given an invalid limit=%d",
(invalidLimit) => {
expect(() => sieveOfEratosthenes(invalidLimit)).toThrow();
}
);
test.each([
[2, [2]],
[3, [2, 3]],
[4, [2, 3]],
[5, [2, 3, 5]],
[6, [2, 3, 5]],
[7, [2, 3, 5, 7]],
[8, [2, 3, 5, 7]],
[9, [2, 3, 5, 7]],
])(
"should return the expected list of primes for limit=%i",
(limit, expected) => {
expect(sieveOfEratosthenes(limit)).toEqual(expected);
}
);
});

describe(primeGenerator, () => {
it("should generate prime numbers", () => {
const expectedPrimes = sieveOfEratosthenes(123);
const primeGen = primeGenerator();
for (const prime of expectedPrimes) {
expect(primeGen.next().value).toBe(prime);
}
});
});