C++ code for checking for prime numbers not working

后端 未结 6 974
暖寄归人
暖寄归人 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

    A small optimization for Will Ness's code, just calculate the sqrt of the number outside the for. The condition check executes many times and has no sense to calculate sqrt each time.

    if( num == 2 ) return true;
    if( num < 2 || num % 2 == 0 ) return false;
    int sqrt = sqrt(num);
    
    for( int i=3; i<=sqrt; i+=2 ){   
            if(num % i == 0){ 
                return false;
            } 
    }
    return true;
    

    So far I think that this is the most efficient way!

提交回复
热议问题