我需要帮助解决我遇到的困难

时间:2014-09-10 23:56:35

标签: java

我正在尝试创建一个计算所有素数的简单程序,但出于某种原因,输出结果为:

0
1
2
3
建立成功

这是我的代码:

    public static void main(String[] args)
{
    boolean per = true;
    for(int num = 0;;num++)
    {
        per = true;
        for(int div = 1;div<=num;div++)
        {
            if(num % div != 0)
            {
                per = false;
            }
        }
        if(per == true)
        {
            System.out.println(num);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你的逻辑已关闭。

尝试使用System.out.println(...)来遍历代码(或使用调试器)。

public static void main(String[] args) {
  boolean per = true;
  for (int num = 0;; num++) {
    per = true;
    for (int div = 1; div <= num; div++) {
      if (num % div == 0) {
        System.out.println(num + " is divisible by "+div);
        per = false;
        break;  //stop looping at first opportunity
      }
    }
    if (per == true) {
      System.out.println(num + " is prime");
    }
  }
}

输出:

0 is prime
1 is divisible by 1
2 is divisible by 1
3 is divisible by 1
4 is divisible by 1
5 is divisible by 1
6 is divisible by 1
7 is divisible by 1
8 is divisible by 1
9 is divisible by 1

所以,这告诉你显然你应该在2开始循环,因为所有数字都可以被1整除。

如果将内循环更改为:

(int div = 2; div < num; div++)

你得到:

2 is prime
3 is prime
4 is divisible by 2
5 is prime
6 is divisible by 2
7 is prime
8 is divisible by 2
9 is divisible by 3

(注意我从2开始外循环,因为0和1通常不被认为是素数。