求前n个素数(C++)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了求前n个素数(C++)相关的知识,希望对你有一定的参考价值。

输入一个输n,输出前n个素数。

技术分享图片
 1 #include<iostream>
 2 #include <math.h>
 3 using namespace std;
 4 
 5 class Sushu
 6 {
 7 public:
 8 
 9     Sushu()
10     {
11         num = 2;
12     }
13 
14     ~Sushu()
15     {
16     }
17 
18     bool isSushu()
19     {
20         for (int i = 2; i <=sqrt(num); i++)
21         {
22             if (num%i == 0)
23                 return false;
24         }
25         return true;
26     }
27 
28     int getSushu()
29     {
30         return num;
31     }
32 
33     void printN_Sushu(int n)
34     {
35         int counter=0;
36         cout << endl;
37         while (counter<n)
38         {        
39             if (isSushu())
40             {
41                 counter++;
42                 cout<<""<<counter<<"个素数是:"<<getSushu()<<endl;                
43                 num++;
44             }
45             else
46             {
47                 num++;
48             }
49         }
50 
51     }
52 
53 private:
54     int num;
55 };
56 
57 int main()
58 {
59     int n;
60     cout << "n的值为:";
61     cin >> n;
62 
63     Sushu sushu;
64     sushu.printN_Sushu(n);
65 
66     return 0;
67 }
View Code

运行结果如下图所示:

技术分享图片

以上是关于求前n个素数(C++)的主要内容,如果未能解决你的问题,请参考以下文章

Meissel Lehmer Algorithm 求前n个数中素数个数 模板

C++判断素数的代码

c++ 组合and判断素数

从 3 到 n 的 C++ 素数

使用递归c ++找到最小的素数

《算法竞赛进阶指南》0x17二叉堆 POJ2442 矩阵取数求前N大