-
-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- add nearestPrime() - add primesUntil() - add tests - update pkg
- Loading branch information
1 parent
f832d2f
commit f301256
Showing
4 changed files
with
85 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/** | ||
* Returns iterator of all prime numbers ≤ given `x` using Sieve of | ||
* Eratosthenes. | ||
* | ||
* @remarks | ||
* Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes | ||
* | ||
* @param x | ||
*/ | ||
export function* primesUntil(x: number) { | ||
if (x < 1) return; | ||
yield 1; | ||
const sieve: boolean[] = []; | ||
const max = Math.sqrt(x) | 0; | ||
for (let i = 2; i <= x; i++) { | ||
if (!sieve[i]) { | ||
yield i; | ||
__updateSieve(sieve, i, x, max); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Returns largest prime number ≤ given `x` using Sieve of Eratosthenes. Returns | ||
* -1 if x < 1. | ||
* | ||
* @remarks | ||
* Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes | ||
* | ||
* @param x | ||
*/ | ||
export const nearestPrime = (x: number) => { | ||
if (x < 1) return -1; | ||
let prime = 1; | ||
const sieve: boolean[] = []; | ||
const max = Math.sqrt(x) | 0; | ||
for (let i = 2; i <= x; i++) { | ||
if (!sieve[i]) { | ||
prime = i; | ||
__updateSieve(sieve, i, x, max); | ||
} | ||
} | ||
return prime; | ||
}; | ||
|
||
/** | ||
* @internal | ||
*/ | ||
const __updateSieve = (sieve: boolean[], i: number, x: number, max: number) => { | ||
if (i <= max) { | ||
for (let j = i * i; j <= x; j += i) sieve[j] = true; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters