简体   繁体   English

为什么我的程序为什么认为4是质数?

[英]Why does my program think 4 is a prime number?

Any idea why this method returns true for '4'? 知道为什么该方法对'4'返回true?

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 . 它返回true,因为循环从2开始并以num / 2 -1结束,在num = 4的情况下为1 That means you never enter the for loop. 这意味着您永远不会进入for循环。

Your for loop should be 您的for循环应为

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

Note that the running time of your loop would be O(num) . 请注意,循环的运行时间为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)) . 这是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. 一种更有效的解决方案是检查2,后跟奇数直到sqrt(n),因为任何高于此数的数字都必须意味着存在小于此的因子。

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循环,因此返回true

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

here num was 4 then num / 2 will be 2 这里num4那么num / 2将是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. 最初,我是2,且不小于2。因此, i < 2将给出假。
So your loop never run. 因此,循环永远不会运行。 and function will return true 并且函数将返回true

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

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