我在使用此 C++ 代码时遇到问题。整数num
是一个我想检查它是否是质数的数字。然而这个程序总是返回 false。这可能很简单,但我找不到任何东西。
for(int i=2;i<num;i++){ //primes are allowed to be divided by 1 so we start at 2
if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
return false;
} else if(i == num){ //if we've already done checks as high as possible and not tripped out yet then report success
return true;
}
}
i == num
永远不会发生,因为你的循环条件是i<num
. Try:
for(int i=2;i<num;i++){ //primes are allowed to be divided by 1 so we start at 2
if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
return false;
} else if(i == num-1){ //if we've already done checks as high as possible and not tripped out yet then report success
return true;
}
}
如下文所指出的,else
这里的条件是多余的,你只需要检查从2到sqrt(num)
- 因为其余因素已经检查过。
根据您想要解决问题的复杂程度,还可以进行更多改进。现实中大多数方法都使用概率算法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)