返回列表 發帖

[作業] 質數 (三) - 10000以內的質數總共有幾個?

本帖最後由 葉桔良 於 2022-12-10 19:31 編輯




10000 -> 1229個
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     int sum=0;
  7.     cout<<"10000以內的質數有: ";
  8.     for(int i=1; i<=10000; i++)
  9.     {
  10.         int n=0;
  11.         for(int j=1; j<=i; j++)
  12.         {
  13.             if(i%j==0)
  14.                  n++;
  15.         }
  16.         if(n==2)
  17.             sum++;
  18.     }
  19.     cout<<sum<<"個"<<endl;
  20.     system("pause");
  21.     return 0;   
  22. }
複製代碼
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {     
  6.     int count=0;
  7.     cout<<"100000以內的質數有:"<<endl;   //11 -> 1, 11
  8.     for(int i=1; i<=100000; i++)         //9  -> 1, 3, 9
  9.     {
  10.         int sum=0;
  11.         for(int j=1; j<=i; j++)
  12.         {
  13.              if(i%j==0)                //sum = 2
  14.                  sum++;   
  15.         }     
  16.         if(sum==2)
  17.         {
  18.             count++;
  19.             //count = count + 1;
  20.             cout<<i<<"\t";   
  21.         }
  22.             
  23.     }
  24.     cout<<endl<<count<<endl;
  25.     system("pause");
  26.     return 0;   
  27. }
複製代碼

此帖僅作者可見

TOP

返回列表