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

0
6
Asked By CuriousCoder42 On

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

Answered By LogicLover73 On

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.

Answered By TechieTommy On

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.

CodeNinja88 -

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.

Answered By CodingQueen On

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.

Answered By BinaryBeast On

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!

Answered By DevDude21 On

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!

GeekGoddess95 -

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

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.