Skip to content

Instantly share code, notes, and snippets.

@sergey-shpak
Last active June 24, 2021 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergey-shpak/042086edc914e735d0842d35bd53ea40 to your computer and use it in GitHub Desktop.
Save sergey-shpak/042086edc914e735d0842d35bd53ea40 to your computer and use it in GitHub Desktop.
// Simple task and this is how it should be done initially,
// btw, I can imagine there are many possible improvements,
// like counting only to half of a number, etc
const isPrimeNumber = (
number,
counter = Math.round(number/2)+1
) => counter >= 2 && new Array(counter)
.fill(0, 2).every((i, idx) => number % idx !== 0)
const printPrimeNumbers = (start, amount) => {
const primeNumbers = []
while (primeNumbers.length < amount){
if(isPrimeNumber(++start))
primeNumbers.push(start)
}
return primeNumbers
}
// 7927
console.log(
printPrimeNumbers(2, 1000)
.pop()
)
@andruby
Copy link

andruby commented Jun 24, 2021

99% correct 👍 . 2 is also a prime

@sergey-shpak
Copy link
Author

sergey-shpak commented Jun 24, 2021

@andruby,

99% correct . 2 is also a prime

sure, you can run printPrimeNumbers(1, 1000) to get also 2 in the results ;)

@sergey-shpak
Copy link
Author

updated with counting to half of a number. - this gives two times less operations)

@sergey-shpak
Copy link
Author

sergey-shpak commented Jun 24, 2021

ha, optimization could be tricky), reverting, gonna think about it more)
updated with optimized version (counting to half of a number) ;)

@sergey-shpak
Copy link
Author

hm, this looks really interesting and according to https://medium.com/indian-thoughts/how-to-find-primes-numbers-203b42ac278e
there is possibility to calculate prime numbers with some pattern, but results are not linear

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment