为什么这个质数会像这样运行?

huangapple go评论64阅读模式
英文:

Why does this prime number work like this?

问题

以下是翻译好的部分:

所以,我正在尝试弄清楚如何创建一个素数程序,现在我知道如何验证一个素数,所以我尝试自由发挥,但似乎编写它需要比通常更多的限制来生成最大到100的素数。我尝试了很多方法,遵循了很多方法,其中许多方法似乎很复杂。但是这个程序似乎非常容易理解,但我仍然有困难理解布尔变量的用途?

public static void main(String[] args) {

    for (int i = 2; i <= 100; i++) {
        boolean primeNum = true;

        for (int j = 2; j < i; j++) {

            if (i % j == 0) {
                primeNum = false;
                break;
            }
        }
        if (primeNum) {
            System.out.println(i);
        }
    }

}
英文:

So I am trying to figure out how to make a prime number program, now I know how to verify a prime number, so i tried to freestyle it, but it seems like programming it requires more restrictions than usual to create prime numbers up to a 100. I tried many ways and followed many methods, many of them seem complex. But this program here seems very easy to understand, but i still have trouble understanding the boolean variable purpose?

 public static void main(String[] args) {

        for (int  i = 2; i &lt;=100; i ++) {
            boolean primeNum = true;

            for (int j = 2; j &lt;i; j++) {

                if (i%j == 0) {
                    primeNum = false;
                    break;
                }
            }
            if (primeNum) {
                System.out.println(i);
            }
        }

    }

答案1

得分: 1

它的功能是对当前数值小于给定数值的每个数值进行取模。如果模值为0,则当前数值可以被整除,因此它不是质数。

当一个数能被除1和自身以外的数整除时,布尔标志会被改变。如果该标志为“true”,则不进行除法操作,该数是质数,并被打印出来;否则,不打印任何内容。

英文:

What it does is make a mod to every number less than the current one. If the modular is 0, then the current number can be divided, hence it is not a prime number.

The boolean flag is changed whenever a number can be divided by a number different than 1 and itself. If the flag is true, then no division happens and it is a prime number and be printed out, otherwise, nothing is printed.

答案2

得分: 0

看起来 primeNum 的目的是用来“保存”它是否是质数,然后将其打印出来。只有在我们遍历了所有的除数(j 的索引)之后,我们才知道它是否是质数。

英文:

Looks like the purpose of primeNum is to "save" whether or not it's a prime, then print it out. We only know whether it's a prime after we've gone through all the divisors (index of j)

huangapple
  • 本文由 发表于 2020年9月18日 05:45:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63946552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定