3 回答
TA贡献1860条经验 获得超8个赞
如果你想打印从 1 到 100 的所有质数,那么你必须遍历所有这些数字(第一个循环),并为它们中的每一个迭代所有可能的除数(嵌套循环):
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,无法应用条件,因此首先打印它们。
我使用了@selbie 的优化提示<= sqrt(number)
TA贡献1845条经验 获得超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++;
}
}
}
添加回答
举报