public class RandomPrime
{
public static void main(String[] args)
{
int squareNumber = readInput();
BigInteger randomPrimes[] = generateRandomPrime(squareNumber);
}
public static BigInteger[] generateRandomPrime(int num)
{
int numberOfPrimes = (int) Math.sqrt(num);
int start, end, step;
start = 1;
step = num / numberOfPrimes;
end = start + (step - 1);
/*int randomPrimes[] = new int[numberOfPrimes];*/
BigInteger randomPrimes[] = new BigInteger[numberOfPrimes];
Random rand = new Random();
int tempPrime;
for (int i = 0; i < numberOfPrimes; i++) {
while (true) {
tempPrime = rand.nextInt(end - start) + start;
if (isPrime(tempPrime)) {
randomPrimes[i] = new BigInteger(tempPrime + "");
System.out.println("Random prime is "+tempPrime);
break;
}
}
start = end + 1;
end = end + (step - 1);
System.out.println("OUTER WHILE");
}
return randomPrimes;
}
public static boolean isPrime(int num)
{
for (int i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static int readInput()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = 0, sqrt;
while (true) {
System.out.println("Enter a square number");
try {
num = Integer.parseInt(br.readLine());
sqrt = (int) Math.sqrt(num);
if (num == (sqrt * sqrt)) {
System.out.println("Entered valid square num is "+num);
break;
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Entered a non square number.So");
}
return num;
}
}
这是我写的代码。我想生成均匀分布的随机素数。这段代码有效。
我的问题:我不确定我的代码是否生成了均匀分布的素数。这是对的吗?如果没有,我该如何解决?