Generating a random prime number in Java
Generating a random prime number in Java
This is how I would do it, however be aware that if you input large numbers into this isPrime
method it will start to lag. Whenever you have an error in your code try unit testing (testing small parts of code). That way you will be able to find and fix your code errors easily, this is why I would highly recommend using some type of isPrime
method, rather than having all the code in the main
method.
public class Prime_Number_Generator {
public static void main(String[] args) {
int num = 0;
Random rand = new Random(); // generate a random number
num = rand.nextInt(1000) + 1;
while (!isPrime(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num); // print the number
}
/**
* Checks to see if the requested value is prime.
*/
private static boolean isPrime(int inputNum){
if (inputNum <= 3 || inputNum % 2 == 0)
return inputNum == 2 || inputNum == 3; //this returns false if number is <=1 & true if number = 2 or 3
int divisor = 3;
while ((divisor <= Math.sqrt(inputNum)) && (inputNum % divisor != 0))
divisor += 2; //iterates through all possible divisors
return inputNum % divisor != 0; //returns true/false
}
}
I think there is a bit of an easier method to generate prime numbers though this one is a little bit slow I think this might help:
public class Prime_number_generator
{
public static int main()
{
int prime;
while (true)
{
int count = 0;
double x = Math.random();
double y = 10000 * x;
double z = Math.ceil(y);
prime = (int)z;
for (int i = 1; i <= prime; i++)
{
int modfactor = prime % i;
if (modfactor == 0)
{
count++;
}
}
if (count == 2)
{
break;
}
}
return prime;
}
}
I hope this is useful to you.