求前n個素數(C++)

來源:互聯網
上載者:User

標籤:ret   soft   i++   tps   space   math.h   hid   strong   microsoft   

輸入一個輸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             else46             {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++)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.