c++ - 如何编写一个程序来显示一个数是否为质数,并可以显示文件中从 1 到 100 的质数

标签 c++ primes

我正在尝试编写一个程序,它会告诉您输入的数字是否为素数,并将 1 到 100 之间的所有素数写入一个文件并显示这些数字。这是我到目前为止所拥有的,但我迷路了。

bool isPrime(int);

int _tmain(int argc, _TCHAR* argv[])
{
    int num, answer, choice, i, numb=1;

    do
    {
        cout<< "Enter a number and I will tell you if it is prime or not."<<endl;
        cin>> num;

        if (isPrime(num))
            cout<<num<<" is a prime number."<<endl;
        else 
            cout<<num<< " is not a prime number."<<endl;

        cout<<"Would you like the first 100 prime numbers displayed? (1 for yes and 2 for no)"<<endl;
        cin>>choice;

        if (choice == 1)
        {
            while(numb<=100)
            { 
                i=2; 

                while(i<=numb)
                { 
                    if(num%i==0)
                        break;

                    i++;
                }

                if(i==num)
                    cout<<numb<<" is Prime"<<endl;

                numb++;
            }
        }
        else
        {
            cout<<"Would you like to run the program again? (1 for yes and 2 for no)"<<endl;
            cin>>answer;

            if (answer == 2)
            {
                exit(0);
            }
        }
        while (answer == 1);
    }

    system("pause");

    return 0;
}

bool isPrime (int number)
{
    int i;

    for (i=2; i<number; i++)
    {
        if (number % i == 0)
        {
            return false;
        }
    }

    return true;    
}

最佳答案

真的觉得你想多了。您已经完成了困难的部分,即编写 isprime 函数。

显示数字很简单,只需编写一个 for 循环遍历数字并检查哪些是素数,如果特定数字是素数则将其打印到屏幕。

然后只需将写入文件的内容添加到循环中,以打印到屏幕上的那些数字。

关于c++ - 如何编写一个程序来显示一个数是否为质数,并可以显示文件中从 1 到 100 的质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5275946/

相关文章:

c++ - 从 C DLL 调用重载的 C++ 函数

c++ - 对指针 vector 进行排序

ruby - 如何生成前 n 个素数?

c++ - QCalendarWidget - 如何突出显示日期

c++ - C++ 模拟创建两个重叠的 win32 窗口

c++ - 非类型模板参数错误 ('x' is not a type)

c++ - 找到除数的数量不知道出了什么问题

python - 我在 Python 中有 2 个代码用于查找素数。为什么在这两个代码中,一个产生结果的速度比另一个快得多

javascript - 试图找出数字是否为奇数/偶数/合数/素数

java - 使用 long 计算素数 (Java)