我的循环查找素数的问题

时间:2015-02-09 18:19:05

标签: c++ loops primes

我需要输出来读取数字,然后数字是否为素数。出于某种原因,当它达到11时它不会输出它是素数并且只是打印 11 12这个数字不是素数。

我知道我的while循环存在逻辑问题,但我无法弄明白。任何帮助表示赞赏。

int main()
{
    bool isPrime = true;

    int sqrtNum;
    int divisor = 3;

    for(int i = 0; i < 100; i++)
    {
        cout << i << "\t";


        if (i == 0 || i == 1)
            cout << "That number is not prime." << endl;
        else if (i == 2)
            cout << "That number is prime." << endl;
        else if (i % 2 == 0)
            cout << "That number is not prime." << endl;
        else
        {
            sqrtNum = static_cast<int> (sqrt(static_cast<double>(i)));

            while (divisor <= sqrtNum)
            {
                if (i % divisor == 0)
                {
                    cout << "That number is not prime." << endl;
                    isPrime = false;
                    break;
                }
                else
                {
                    divisor = divisor + 2;
                }
            }
            if (isPrime)
            {
                cout << "That number is prime" << endl;
            }
        }

    }
    system("pause");
    retu

1 个答案:

答案 0 :(得分:3)

从评论中可以清楚地看到,您忘记在循环中重置isPrimedivisor的值。为了避免这样的错误,最好只在使用它们的范围内定义这些变量。

int main()
{
    for(int i = 0; i < 100; i++)
    {
        cout << i << "\t";


        if (i == 0 || i == 1)
            cout << "That number is not prime." << endl;
        else if (i == 2)
            cout << "That number is prime." << endl;
        else if (i % 2 == 0)
            cout << "That number is not prime." << endl;
        else
        {
            bool isPrime = true;
            int divisor = 3;
            int sqrtNum = static_cast<int> (sqrt(static_cast<double>(i)));