在给定间隔内搜索素数时输出错误

时间:2016-04-25 22:33:12

标签: c++ c++11

我试图找到num1num2之间的素数,但如果输入为1,10,则此代码仅产生1,2,3作为素数

#include <iostream>
using namespace std;
void prime(int num1, int num2)
{
    bool prime = 1; // prime=1 means the number is prime
    for (num1; num1 <= num2; num1++)
    {
        for (int i = 2; i < num1; i++)
        {
            if (num1 % i == 0)
            {
                prime = 0;
                break;
            }
        }

        if (prime == 0)
        {
            cout << num1 << " Is not Prime" << endl;
        }
        else
        {
            cout << num1 << " Is prime" << endl;
        }
    }
}

int main()
{
    int num1, num2;
    cout << "Enter 2 numbers to check the prime numbers between them:";
    cin >> num1 >> num2;
    prime(num1, num2);
}

3 个答案:

答案 0 :(得分:2)

在开始循环候选素数之前,您只需设置prime=1一次。因此,只要您点击一个不是素数的数字(在您的情况下为4),您就会得到prime=0,然后它再也不会被设置为1。

答案 1 :(得分:0)

的第二个应该从3变为(int)sqrt((double)num2),步骤 i + = 2

答案 2 :(得分:0)

您忘记将bool prime重置为true。

试试这个......

#include <iostream>
using namespace std;
void prime(int num1, int num2)
{
    for (num1; num1 <= num2; num1++)
    {    
        bool prime = 1; // prime=1 means the number is prime
        for (int i = 2; i < num1; i++)
        {
            if (num1 % i == 0)
            {
                prime = 0;
                break;
            }
        }

        if (prime == 0)
            cout << num1 << " Is not Prime" << endl;
        else
            cout << num1 << " Is prime" << endl;
    }
}

int main()
{
    int num1, num2;
    cout << "Enter 2 numbers to check the prime numbers between them:";
    cin >> num1 >> num2;
    prime(num1, num2);
}