+ 6

# How to get random prime numbers in Java?

I am currently working on a Java project that generates random numbers. The project contains a filter to prevent the code from outputting prime integers. At first, the filter only needed to filter prime integers up to 100. Typing prime numbers up to 100 is not too hard, but further into the code I found out that I need to expand the filter so that it would filter prime integers up to 10100. And obviously I didn't want to write prime numbers up to 10100. Could someone help me? Sorry for long post

1 Answer

+ 9

Create a boolean method that checks if a number is prime. Use that method in a while loop so as to check for if the number generated is prime. If it is, take it. Else generate again.
Random rand = new Random();
// generate a random number
int num = rand.nextInt(10100) + 1;
while (!isPrime(num)) {
num = rand.nextInt(10100) + 1;
}
It is somewhat slow for big numbers, obviously.