What's the Best Way to Generate a Random Prime Number Between 100 and 2000?

April 9, 2026 5 answers
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

+next_attempt
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!

Grommet: Absolutely! You get immediate results without any back-and-forth checking, which is what makes it the clear choice.

Reply to this answer
!WatchYourStep
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
0p2um-filter
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
_sleeve_notes
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
wind12kt
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.

Related Discussions