简体   繁体   中英

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. However, it's not working properly because of the while loop. After execution, this program lists all prime numbers less than 1000. It seems that the while loop is not functioning at all. Can anyone tell me the reason? Many thanks.

The primes are generated by the first for loop. The while body is only executed once.

You could remove the while and instead use a different condition on the 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

Why are you not writing a boolean isPrime(int number) function? 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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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