简体   繁体   English

为什么这个质数会这样工作?

[英]Why does this prime number work like this?

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.所以我试图弄清楚如何制作一个质数程序,现在我知道如何验证一个质数,所以我尝试自由式它,但似乎编程需要比平时更多的限制来创建质数100.我尝试了很多方法,遵循了很多方法,其中很多看起来很复杂。 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 <=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);
            }
        }

    }

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.如果模数为 0,则当前数可以被整除,因此它不是素数。

The boolean flag is changed whenever a number can be divided by a number different than 1 and itself.每当一个数字可以被一个不同于 1 和它本身的数字整除时, boolean标志就会改变。 If the flag is true , then no division happens and it is a prime number and be printed out, otherwise, nothing is printed.如果标志为true ,则不会发生除法,并且它是质数并打印出来,否则不打印任何内容。

Looks like the purpose of primeNum is to "save" whether or not it's a prime, then print it out.看起来 primeNum 的目的是“保存”它是否是素数,然后将其打印出来。 We only know whether it's a prime after we've gone through all the divisors (index of j)我们只有在经过所有除数后才知道它是否是素数(j 的索引)

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

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