Reputation: 13
I am trying to make a program that generates a pseudo random number and checks if it is prime. Then the program will loop until the random number is a prime. However, it does not always print a prime number.
public class Prime_Number_Generator {
public static void main(String[] args) {
int[] primesList = {2, 3, 5, 7, 11, 13, 17, 19}; // list of known primes
int num = 0;
int i = 0;
int counter = 1;
Random rand = new Random(); // generate a random number
while (i != counter) {
num = rand.nextInt(1000) + 1;
if (num % primesList[i] == 0) // check if num is evenly divisible by a prime from the list
i++;
}
else { // if it is prime exit loop
i = 0;
counter = 0;
}
}
System.out.println(num); // print the number
}
}
Upvotes: 1
Views: 18359
Reputation: 55
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.
Upvotes: 0
Reputation: 643
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
}
}
Upvotes: 2