繁体   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");
        }       
    }
}

}
}

这是我编写的程序,用于列出前50个素数,每行十个素数。 但是,由于while循环,它无法正常工作。 执行后,该程序将列出所有小于1000的质数。while循环似乎根本不起作用。 谁能告诉我原因? 非常感谢。

质数由第一个for循环生成。 while主体仅执行一次。

您可以删除while ,而对for使用不同的条件:

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

你有一个大问题,真正的代码如下:

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");
         }  
    }    
}

输出为: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

为什么不编写布尔isPrime(int number)函数? 您将必须检查它是否为真,如果是,则增加计数器并打印数字。 这是一个简单的实现,我看到了其他一些更好的实现:

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;
}

在您的内部:

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