4 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個贊
您的isPrime(int)函數(shù)應(yīng)如下所示:
public static boolean isPrime(int n) {
for (int div = 2; div < n; div++) {
if (n % div == 0) { // n is not prime
return false;
} else {
return true;
}
}
return false;
}
您的實(shí)施不起作用,因?yàn)椋?/p>
你沒有
boolean
從函數(shù)中返回Java 是按值傳遞的,因此您的變量
isPrime
不會更新
還要確保不要混淆素數(shù)和奇數(shù)之間的差異。

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個贊
您的實(shí)施不起作用,因?yàn)椋?/p>
你沒有boolean從函數(shù)中返回
Java 是按值傳遞的,因此您的變量isPrime不會更新
還要確保不要混淆素數(shù)和奇數(shù)之間的差異。

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個贊
public class lab7 {
public static boolean isPrime(int n,boolean isPrime){
for (int div = 2; div < n; div++) {
if (n % div == 0) { // n is not prime
isPrime = false;
div = n;
}else{
isPrime=true;
}
}
return isPrime;
}
// This program prints out the first 100 prime numbers
public static void main(String[] args) {
int count = 0;
int n = 1;
boolean isPrime=true;
// loop that iterates 100 times
while (count <= 100) {
// Use the isPrime method to check whether
// the number n is prime or not
if (isPrime(n, isPrime)) {
System.out.println(n + " is prime");
count++;
}
// move on to the next n
n++;
}
}
}
我已經(jīng)更正了代碼。請檢查。
添加回答
舉報