输入一个输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 }
运行结果如下图所示:
时间: 2024-10-11 23:20:01