我是一名业余Java学生,我的老师给了我这个作业,写了一个列出前100个质数的代码。到目前为止,这是我尝试过的。
for(int i =1; true; i++) {
int k = 0;
for(int j = 1; j <= i; j++) {
if(i % j == 0){
k ++;
}
if(k == 2) {
System.out.println(i);
}
}
}
我遇到的问题是,即使我使用了我熟悉的可能的机制,在计数100后我也无法停止控制台停止。例如:
for( int i =1; true; i++) {
int k = 0;
for(int j = 1; j <= i; j++) {
if(i % j == 0) {
k ++;
}
int m = 0;
if(k == 2) {
System.out.println(i);
m++;
if(m==100) {
break;
}
}
}
}
计数100个素数后,我是否可以终止循环?
答案 0 :(得分:2)
您需要跟踪已打印的质数,直到达到100停止打印。我已经使用代码中的注释解释了以下代码。
public class Main
{
public static void main(String[] args) {
int k = 0; // to keep track of how many primes you have prited
int i = 2; // number to check for prime, increases every loop
while (k < 100){ // while you have printed less than 100 primes
boolean isPrime = true; // next few lines are checking i for prime and store it in this variable
for(int divisor = 2; divisor <= i / 2; divisor++) { // you should go with divisor <= Math.sqrt(i) in condition, I couldn't be bothered in import stuff.
if (i % divisor == 0) {
isPrime = false;
break; // i is not a prime, no reason to continue checking
}
}
if (isPrime){
System.out.println(i); // if i is prime, print it
k ++; // increase k by when a print number is found
}
i ++; // increase i to check next number
}
}
}
答案 1 :(得分:1)
您的代码运行到无穷远,因为您将break
放错了位置。 break
退出了for(int j = 1; j <= i; j++)
的内循环,尽管您应该将外循环for( int i =1; true; i++)
定位为目标,因为那是决定要打印多少个内循环的原因如果数字是素数。
我已在代码中更正了您的方法(解释在注释中)
int numbersPrinted = 0; // To keep track of how many numbers have been printed
for (int i = 2; true; i++) {
boolean isPrime = true; // Assuming the number is prime
for (int j = 2; j < i; j++) {
// Checking if any number from 2 to i-1 completely divides i
if (i % j == 0) {
// If a number completely divides (gives 0 remainder)
// The number is not prime
isPrime = false;
// You can use break here. I don't think it matters anyways.
}
}
if (isPrime) {
// Printing i only if it is prime
System.out.print(i + ", ");
numbersPrinted++; // Updating the numbersPrinted
}
// Checking if the numbers printed is grater than or equal to 100
if (numbersPrinted >= 100)
// This will break the outermost loop
// This is where you messed up
break;
}
输出(恰好100个质数)
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
答案 2 :(得分:0)
要回答您如何在100处停下来:
for( int i =1; i<=100; i++){
for语句的第二个参数是继续的条件。如果此条件的计算结果为false,则for循环将停止迭代。