简体   繁体   中英

Finding and Printing all Prime numbers from 1 to N

Here is what I have so far, and I am usually pretty good at tracing programs but i just can't figure out where i got stuck. It's supposed to get "N" and Mod it by D, which equals N-1, while D is greater than 1. And once it is done, it goes on the one number less than the original one, and does the same thing while N is greater than 2. And as for the "Count", i just added it so that I could check if the number was prime. Ex: if the count = N-2, which is basically every number from 2 to N-1, then that number is prime.

public class Challenge14 {
  public void inti() {
    int count = 0;
    int N = 7;
    int D = N - 1;
    int A = 0;

    while (N > 2) {
      D = N - 1;

      while (D > 1) {
        A = N % D;
        D--;

        if (A == 0) {
          break;
        }

        else {
          count++;
        }
      }

      if (count == N - 2) {
        System.out.println(N);
      }
      N--;
    }
  }
}

Use a for loop.

for (int i = 1; i<N; i++) {
System.out.println(i);
}

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