C++ code for checking for prime numbers not working

后端 未结 6 932
暖寄归人
暖寄归人 2021-01-29 05:24

I\'m having trouble with this C++ code. The integer num is a number that I want to check if it is prime. However this program is always returning false. It\'s proba

6条回答
  •  悲&欢浪女
    2021-01-29 05:48

    You don't have to check every number, as a lot of them can easily be ruled out. For example, after checking that num is not divisible by 2, you can skip all other even numbers. That saves you half the tests.

    We also definitely know that any other factor must be less than num/2 (or really sqrt(num), but that is harder to compute). That knowledge can save us another half of the tests.

    So now we have:

    if (num % 2 == 0)
        return false;
    
    for(int i = 3; i < num / 2; i += 2){ 
         if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
             return false;
         }
    }
    
    // arriving here we have found no factors, so it must be a prime
    return true;
    

提交回复
热议问题