Skip to content

Commit

Permalink
Optimize the primality check
Browse files Browse the repository at this point in the history
  • Loading branch information
frostburn committed Dec 19, 2023
1 parent de21aa7 commit 68604ca
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/__tests__/primes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ describe('Primeness detector', () => {
expect(isPrime(n)).toBe(false);
}
});
it('works for 62837327', () => {
expect(isPrime(62837327)).toBe(false);
});
it('works for 62837303', () => {
expect(isPrime(62837303)).toBe(true);
});
});

describe('Lists of primes', () => {
Expand Down
3 changes: 3 additions & 0 deletions src/primes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ export function isPrime(n: number) {
throw new Error('Prime check only implemented up to 62837328');
}
for (const prime of PRIMES) {
if (prime * prime > n) {
return true;
}
if (n % prime === 0) {
return false;
}
Expand Down

0 comments on commit 68604ca

Please sign in to comment.