3 回答
TA貢獻1842條經(jīng)驗 獲得超22個贊
您的代碼應(yīng)該具有嵌套循環(huán)和一個數(shù)組,該數(shù)組存儲要在最后顯示的素數(shù)。
要在最后打印它們,您應(yīng)該首先打印您的語句,然后使用循環(huán)打印包含找到的素數(shù)的數(shù)組。
TA貢獻1860條經(jīng)驗 獲得超8個贊
如果你想打印從 1 到 100 的所有質(zhì)數(shù),那么你必須遍歷所有這些數(shù)字(第一個循環(huán)),并為它們中的每一個迭代所有可能的除數(shù)(嵌套循環(huán)):
int number = 100;
boolean isPrime = false;
System.out.println("2");
System.out.println("3");
for (int i = 5; i <= number; i++) {
for (int divisor = 2; divisor <= Math.sqrt(i); divisor++) {
isPrime = !(i % divisor == 0);
if (!isPrime)
break;
}
if (isPrime)
System.out.println("" + i);
}
請注意,對于 2 和 3,無法應(yīng)用條件,因此首先打印它們。
我使用了@selbie 的優(yōu)化提示<= sqrt(number)
TA貢獻1845條經(jīng)驗 獲得超8個贊
我要感謝大家的建議和提示。以及推動我的動力。我能夠讓程序運行。見下文
public class primes {
public static void main (String[] args) {
final int NUMBER_OF_PRIMES = 26; // Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 5; // Display 5 numbers per line
int count = 0; // Count the number of prime numbers
int number = 1; // A number to be tested for primeness
System.out.println("The prime numbers between 1 and 100 are \n");
// Repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES) {
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test whether number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true, number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
// Display the prime number and increase the count
if (isPrime) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Display the number and advance to the new line
System.out.println(number);
}
else
System.out.print(number + " ");
}
//Check if the next number is prime
number++;
}
}
}
添加回答
舉報
