用于检查素数不工作的C ++代码 [英] C++ code for checking for prime numbers not working

查看:109
本文介绍了用于检查素数不工作的C ++代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用这个C ++程式码时遇到问题。整数 num 是一个数字,我想检查它是否为素数。但是这个程序总是返回false。这可能很简单,但我找不到任何东西。

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 probably something simple but I can't find anything.

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;
        }
}


推荐答案

code> i == num 永远不会发生,因为你的循环条件是 i 。尝试:

i == num will never occur, since your loop condition is 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) - 因为其余的因素已经检查。

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.

这篇关于用于检查素数不工作的C ++代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆