我在使用此C++代碼時遇到問題。整數num
是我想檢查它是否爲素數的一個數字。但是這個程序總是返回false。這可能很簡單,但我找不到任何東西。用於檢查素數不工作的C++代碼
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;
}
}
謝謝,這是有效的。將接受10分鐘(當它讓我) – stackunderflow 2012-08-01 06:44:14
for(i == 2; i
2012-08-01 06:48:52
沒有必要迭代到'num'。迭代到'num/2'就足夠了。 – cppcoder 2012-08-01 06:52:44