C++ code for checking for prime numbers not working

后端 未结 6 878
暖寄归人
暖寄归人 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-29 06:11

    i == num will never occur, since your loop condition is i. Try:

    for(int i=2;i

    As pointed out below, the else condition here is redundant, and you only need to check from 2 to sqrt(num) - since the remaining factors have already been checked.

    There are more improvements that can be made depending on how complex you want to make the problem. Most methods in reality use probabilistic algorithms.

提交回复
热议问题