我正在制作一个C ++程序,该程序可让您输入数字并检查其是否为质数。但它说像9、15和21这样的数字是素数。我可以帮忙吗? 这很令人困惑。这是我检查其是否为素数的函数:
bool isPrime(int num) {
int w = 2;
while (w <= num) {
if (w % num == 0) {
return false;
}
else if (w < num){
w = w + 1;
}
if (w == num) {
w = 0;
return true;
}
}
}
答案 0 :(得分:2)
已经发现了实际的错误(用w % num
代替了num % w
),只是一些附加提示:
您的代码太复杂了!
while (w <= num) // why <=? w == num is irrelevant, in worst
// case, it will lead to false negatives (num % num == 0)!
{
if (num % w == 0) // (already fixed!)
{
return false;
}
else if (w < num)
{
w = w + 1;
}
if (w == num) // as you increment by 1, this will always be false unless
// previous test failed - so simply use else instead
{
w = 0;
return true;
}
}
第一步:
while (w < num)
{
if (w % num == 0)
{
return false;
}
/*else*/ if (w < num) // however, this check is repeated in the while
// loop anyway; no need to do the work twice
{
++w; // shorter...
}
else
{
// w = 0; // obsolete, we will be destroyed afterwards anyway...
return true;
}
}
第二步:
while (w < num)
{
if (w % num == 0)
{
return false;
}
++w; // at some point, will reach w == num and the loop won't be re-entered
}
// we did not leave the loop prematurely (-> non-prime), so we are prime:
return true;
优化:
num == n * m
和n
大于sqrt(num)
,则m
较小!因此,选中m时n
将已经被捕获,因此您不必检查大于平方根的值。这将已经排除大量数字。n
不代表num
,那么k * m
也不会。对于2的倍数,这太简单了,不能从中获利(尽管仍然相当容易,但考虑到3、5的倍数,则变得更加复杂。)应用这些:
if(num % 2 == 0)
return false;
int w = 3;
while (w*w <= num) // be aware that I had an error here in my comment
// to the question - cannot fix it any more, though...
{
if(num % w == 0)
return false;
w += 2;
}
return true;
答案 1 :(得分:2)
当您意识到大于3的所有素数都可以写为 6n + 1 或 6n + 5 时,可以获得最高solution of Aconcagua的速度。对于自然的 n 。甚至更进一步,所有大于5的素数都可以写为 30n + m ,其中 m 在 {1,7,11,13,17,19, 23,29} 。这就是所谓的Wheel factorization。
这简单理解为:
因此,将Wheel分解系数设置为6,可以快速得出:
if (num == 1) return false;
if (num < 4) return true;
if (num % 2 == 0) return false;
if (num % 3 == 0) return false;
int w = 5;
while (w*w <= num)
{
if(num % (w-2) == 0) return false;
if(num % w == 0) return false;
w += 6;
}
return true;
该算法的运行速度应为阿空加瓜解决方案速度的2/3。
备注:车轮分解系数为30只会产生较小的加速,因为它只消除了序列 30n + 25 ,该序列也被6的车轮分解系数所覆盖 6 *(5 * n + 4)+1 。
备注:仍然测试不应测试的数字,例如( w = 25 ,而我们已经知道 w-2 = 5 经过测试,同上35,49,...)
如果您想变得更健壮并使用一些内存,您可能会对Sieve of Eratosthenes感兴趣。
其他有用的信息可以在这里找到:primes
答案 2 :(得分:0)
我相信你想要
if(w % num == 0)
不
<select class="form-control"
ng-model="vm.gradeSelected">
<option ng-repeat="gradeObj in vm.gradeList" ng-selected="vm.gradeSelected" ng-value="{{gradeObj.grade}}"> {{gradeObj.grade}} - {{gradeObj.category}}</option>
</select>
答案 3 :(得分:0)
此代码可能会帮助`bool isPrime(int num)
int w = 2;
while (w <= num) {
if (num % w == 0) {
return false;
}
else if (w < num){
w = w + 1;
}
if (w == num) {
w = 0;
return true;
}
}
`