简体   繁体   English

查找并打印从1到N的所有素数

[英]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. 它应该得到“ N”,并用D对其进行修改,D等于N-1,而D大于1。完成后,它继续比原始数少一个数,而在N大于2。至于“计数”,我刚刚添加了它,以便可以检查数字是否为质数。 Ex: if the count = N-2, which is basically every number from 2 to N-1, then that number is prime. 例如:如果count = N-2(基本上是从2到N-1的每个数字),则该数字为质数。

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循环。

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

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

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