lpdc99 2022-06-06 19:21 采纳率: 75%
浏览 24
已结题

请编写一个函数,确定一个数是否为质数

请编写一个函数,确定一个数是否为质数。在程序中调用此函数来确定并打印1~10000之间的所有质数。
输出格式:
每数宽度为6,每行输出10个数。

实例输出:
The prime numbers from 1 to 10000 are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
……
9643 9649 9661 9677 9679 9689 9697 9719 9721 9733
9739 9743 9749 9767 9769 9781 9787 9791 9803 9811
9817 9829 9833 9839 9851 9857 9859 9871 9883 9887
9901 9907 9923 9929 9931 9941 9949 9967 9973
There were 1229 prime numbers

参考程序模板:

#include <iostream>
using namespace std;
#include <iomanip>

/* write prototype for function prime */

int main()
{
    int count = 0;

    cout << "The prime numbers from 1 to 10000 are:\n";

    for ( int loop = 2; loop <= 10000; ++loop ) {
        if( /* make call to function prime */ ) {
            ++count;
            cout << setw(6) << loop;

            if (count % 10 == 0)
                cout << '\n';
        }
    }
    cout << '\n' << "There were " << count
        << " prime numbers\n";
    return 0;
}

bool prime( int n )
{
    for( int i = 2; /* write loop condition */; i++)
        if( /* write code to test if n is divisible by i */ )
            return false;

    return true; //number is prime
}

  • 写回答

2条回答 默认 最新

  • A Python 萌新花花 2022-06-06 19:33
    关注
    
    #include <iostream>
    using namespace std;
    #include <iomanip>
     
    bool prime(int n);
     
    int main()
    {
        int count = 0;
     
        cout << "The prime numbers from 1 to 10000 are:\n";
     
        for ( int loop = 2; loop <= 10000; ++loop ) {
            if( prime(loop) ) {
                ++count;
                cout << setw(6) << loop;
     
                if (count % 10 == 0)
                    cout << '\n';
            }
        }
        cout << '\n' << "There were " << count
            << " prime numbers\n";
        return 0;
    }
     
    bool prime( int n )
    {
        for( int i = 2; i<n; i++)/*这个可以写i<sqrt(n)的*/
            if( n%i == 0)
                return false;
     
        return true; //number is prime
    }
     
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月15日
  • 已采纳回答 6月7日
  • 创建了问题 6月6日

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效