简体   繁体   English

while循环中不存在(java代码)

[英]not existing while loop (java code)

public class Q3
{
public static void main(String args[]){
int i, j;
int Max = 1000;
    //It's obvious that the first fifty prime numbers are less than 1000.
int counter = 1;
while (counter <= 50){
    for (i = 2; i < Max; i++){
        for (j = 2; j < i; j++){
            if ( i % j == 0){
            break;
            }
        }
        if (j >= i){
            System.out.printf("%s ", i);
            counter++;
        }
        if(counter % 10 == 0){
        System.out.print("\n");
        }       
    }
}

}
}

This is a program that I wrote to list first 50 prime numbers, ten of them per line. 这是我编写的程序,用于列出前50个素数,每行十个素数。 However, it's not working properly because of the while loop. 但是,由于while循环,它无法正常工作。 After execution, this program lists all prime numbers less than 1000. It seems that the while loop is not functioning at all. 执行后,该程序将列出所有小于1000的质数。while循环似乎根本不起作用。 Can anyone tell me the reason? 谁能告诉我原因? Many thanks. 非常感谢。

The primes are generated by the first for loop. 质数由第一个for循环生成。 The while body is only executed once. while主体仅执行一次。

You could remove the while and instead use a different condition on the for : 您可以删除while ,而对for使用不同的条件:

for (i = 2; counter <= 50; i++){

you have a big problem, the true code is following: 你有一个大问题,真正的代码如下:

int i, j;
int Max = 1000;
//It's obvious that the first fifty prime numbers are less than 1000.
int counter = 0;
for (i = 2; i < Max && counter < 50; i++){
    for (j = 2; j < i; j++){
        if ( i % j == 0){
        break;
        }
    }
    if (j >= i){
        printf("%d ", i);
        counter++;
         if(counter % 10 == 0){
             printf("\n");
         }  
    }    
}

the output is: 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 输出为: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 139 149 151 157 163 167 173 179 181 181 191 193 197 199 199 211223227229

Why are you not writing a boolean isPrime(int number) function? 为什么不编写布尔isPrime(int number)函数? You will have to check if it is true, and if it is, increase the counter and print the number. 您将必须检查它是否为真,如果是,则增加计数器并打印数字。 Here is a naive implementation, I have seen some other better implementations: 这是一个简单的实现,我看到了其他一些更好的实现:

boolean isPrime(int number) {
  if (number < 2 || number % 2 == 0) {
    return true;
  }
  double sqrt = Math.sqrt(number);
  for (int i = 3; i <= sqrt; i += 2) {
    if (number % i == 0) {
      return true;
    }
  }
  return false;
}

Inside your for: 在您的内部:

for (i = 2; i < max; i++) {
  if (isPrime(i)) {
    counter++;
    // print number, print new line if needed
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM