简体   繁体   中英

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. 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.

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.

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)

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