简体   繁体   中英

Why does my program think 4 is a prime number?

Any idea why this method returns true for '4'?

private boolean isPrime(int num) {
            if (num < 2) {
                return false;
            }
            for (int i = 2; i < num / 2; i++) {
                if (num % i == 0)
                    return false;
            }
            return true;
}

It returns true since your loop starts from 2 and ends in num / 2 -1 which in the case of num = 4 is 1 . That means you never enter the for loop.

Your for loop should be

for (int i = 2; i <= num/2; i++)

Note that the running time of your loop would be O(num) . For more efficiency you might want to consider the loop

for (int i = 2; i * i <= num; i++)

which is O(sqrt(num)) .

A more efficient solution is to check for 2 followed by odd numbers up to the sqrt(n) as any number above this would have to mean there is a factor less than this.

static boolean isPrime(long num) {
    if (num < 2) return false;
    if (num == 2) return true;
    if ((num & 1) == 0) return false; // must be even
    for (int i = 3, max = (int) Math.sqrt(num); i <= max; i += 2)
        if (num % i == 0) 
            return false;
    return true;
}

It is returning true because control never got inside of for loop.

for(int i = 2; i < num / 2; i++) { ... }

here num was 4 then num / 2 will be 2

for(int i = 2; i < 2; i++) { ... }

And initially i is 2 which is not less than 2. So i < 2 will give false.
So your loop never run. and function will return true

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