我试图创建一个函数来给出最接近的素数到该人输入的数字,并且我没有成功。顺便说一下,我现在开始编程并且循环让我困惑,任何提示? 这是以下代码:
public static void main(String[] args) {
// Entry Mechanism
Scanner input = new Scanner(System.in);
// Variables
int n1, biggestPrime;
System.out.print("Number: ");
n1 = input.nextInt();
biggestPrime = biggestPrime(n1);
}
public static int biggestPrime(int n1) {
int biggestPrime = 0;
boolean isPrime = true;
if (n1 < 0)
return 0;
for (int i = n1; i == 0 && isPrime == false; i--) {
if (i % n1 == 0) {
isPrime = false;
}
}
return biggestPrime;
}
答案 0 :(得分:2)
我认为你不会试图找到素数的最大素数...
public static void main(String[] args) {
// Entry Mechanism
Scanner input = new Scanner(System.in);
// Variables
int n1, biggestPrime;
System.out.print("Number: ");
n1 = input.nextInt();
biggestPrime = biggestPrime(n1);
}
public static int biggestPrime(int n1) {
int biggestPrime = 0;
int num_max = 100000;
if (n1 < 0) {
return 0;
}
else {
for (int i = n1; i< num_max; i++) {
for (int j = 2; j < Math.sqrt(i); j++) {
System.out.println(j + " " + i);
if (i==j) {
biggestPrime = i;
// break:
j = num_max;
i = num_max;
}
if (i % j == 0) {
break;
}
}
}
}
return biggestPrime;
}