Last active
April 4, 2024 18:37
-
-
Save FaberVitale/4365404247f8b68051d7c822c62f985e to your computer and use it in GitHub Desktop.
prime numbers
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
function* primeNumbers() { | |
const primeList = [2, 3]; | |
let nextCandidate = 4; | |
yield 1; | |
yield 2; | |
yield 3; | |
while(true) { | |
if(primeList.every(prime => nextCandidate % prime !== 0)) { | |
yield nextCandidate; | |
primeList.push(nextCandidate); | |
} | |
nextCandidate++; | |
} | |
} | |
function isPrime(n: number): boolean { | |
if (n <= 0) { | |
return false; | |
} | |
if (n <= 3) { | |
return true; | |
} | |
let i = 2; | |
while (i <= Math.sqrt(n)) { | |
if (n % i === 0) { | |
return false; | |
} | |
i++; | |
} | |
return true; | |
} | |
function getPrimeWithDigits(maxDigits: number): number { | |
let primeDigits = 0; | |
let num = 1; | |
while (true) { | |
const isPrimeNumber = isPrime(num); | |
if (isPrimeNumber) { | |
primeDigits += num.toFixed(0).length; | |
if (primeDigits >= maxDigits) { | |
break; | |
} | |
} | |
num++; | |
} | |
return num; | |
} | |
// Tests | |
[1_000].forEach((num) => { | |
const primeWithDigits = getPrimeWithDigits(num); | |
console.log(`primeDigits: num=${num} ouput=${primeWithDigits}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment