在 Java 中生成随机素数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24006143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating a random prime number in Java
提问by user3693264
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
}
}
采纳答案by Stephen Buttolph
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 highlyrecommend using some type of isPrime
method, rather than having all the code in the main
method.
我就是这样做的,但是请注意,如果您在此isPrime
方法中输入大量数字,它将开始滞后。每当您的代码出现错误时,请尝试单元测试(测试代码的一小部分)。这样你就可以很容易地找到并修复你的代码错误,这就是为什么我强烈建议使用某种类型的isPrime
方法,而不是在main
方法中包含所有代码。
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
}
}