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?
5 Answers
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.
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.
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.
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!
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!
Absolutely! You get immediate results without any back-and-forth checking, which is what makes it the clear choice.

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.