C++ code for checking for prime numbers not working

后端 未结 6 977
暖寄归人
暖寄归人 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 06:05

    Here's the proper way to write what you meant:

    int i=2;                     // move declaration out
    for(/*int i=2*/;i

    But that's not efficient. You only have to check for i's not exceeding of sqrt(num). Plus, if you check num%2, there's no more need to check any other even numbers, so you can use an increment of 2. Or you can even count by 6:

    if( num == 2 || num == 3 ) return true;
    if( num < 2 || num % 2 == 0 || num % 3 == 0 ) return false;
    for( int i=5, j=7, lim=sqrt(num); i<=lim; i+=6, j+=6 ){   
            if( num % i == 0 || num % j == 0 ){ 
                return false;
            } 
    }
    return true;
    

    (notice: this is more efficient than another answer here, which says it's an "optimization" of an initial version of this answer).

提交回复
热议问题