What's the Best Way to Generate a Random Prime Number Between 100 and 2000?
Asked by
rEsetButton
I'm working on a static HTML/JS page and need it to display a random prime number in the range of 100 to 2000. I have a couple of methods I could use: 1) Keep generating random numbers until I get a prime, or 2) Create a list of all primes in that range once and then randomly pick from that list. I'm curious about your thoughts on which option would be better to implement and why?
Answers
For me, it's all about efficiency. The second method saves processing time by not having to check for primes every time. Just grab a random index from your precomputed list, and you're done!
Reply to this answer
Storing the primes doesn't take much memory compared to what you're saving in processing time. Just hardcode the list or generate it at startup and you're all set!
Reply to this answer
I avoid the rerolls because of how inefficient they can be. There aren't that many primes between 100 and 2000, so randomly rolling is a big waste of timeโdefinitely go with the precomputed list.
Reply to this answer
I would definitely go with the second option. Generating the primes once and then just picking one is way more efficient. The first method could end up running forever in the worst case, which isn't ideal.
okra+harvest: Exactly! Plus, the overhead of generating random numbers over and over just for a prime isn't worth it when you can have a ready-made list.
Reply to this answer
I think it depends on how many times youโll access the page. If itโs just for a few random primes here and there, generating on the fly could be fine. But if itโs going to be hit a lot, then definitely opt for the list approach.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Grommet: Absolutely! You get immediate results without any back-and-forth checking, which is what makes it the clear choice.