Advertisement
uopspop

Untitled

Apr 26th, 2016
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4. using namespace std;
  5. const int maxn = sqrt(2147483647);
  6. vector<bool> c(maxn,0);  //判斷0~46340間的質數,並標記為false
  7. vector <int> p;    // 篩出並存入 0~46340間的質數
  8. //2~46340之間的質數共有 4792個
  9. //  p[4791]=46337 , p[4790]=46327,p[4792]=46349
  10.  
  11. // 以下 isp 為函式, 傳入 n 判斷是否為質數
  12. bool isp(int n)
  13. {
  14.   if(n<=maxn) return( !c[n] );
  15.   int q = (int) sqrt(n);
  16.   int k;
  17.   for(k=0; k<p.size() && p[k]<=q ; ++k)
  18.     if(n%p[k]==0) return false;
  19.   return true;    
  20. }
  21. // 篩法建 c[0..46340] 及 vector <int>
  22. void sieve()
  23. {
  24.   int i,j,k;
  25.   c[0]=c[1]=1;
  26.   for(i=2;i<=maxn;++i)
  27.   {
  28.      if(c[i]==1) continue; //非質數
  29.      p.push_back(i);  // i是質數,放入 p 中 // 第一個碰到的數是質數,其後之倍數就都不是了 ex, 2, 3 , 5, 7 ...
  30.      //是質數的倍數 註記為非質數
  31.      for(j=i+i; j<=maxn; j+=i)
  32.        c[j]=1;                  
  33.   }
  34. //    for(k=2; k<=100; ++k)  // 印出 2~100的質數
  35. //      if( !c[k] ) cout << k << endl;
  36. //    cout << p.size() <<" " << p[p.size()-1] << endl;
  37.   return ;
  38. }
  39. // 主程式
  40. int main()
  41. {
  42.   sieve(); //建質數表,有bool c[] 及 vector <int> p
  43.   int n;
  44.   while( cin >> n )
  45.   {
  46.     bool final = isp(n);  
  47.     if (final == true) {
  48.         cout << "質數" << endl;        
  49.     } else if(final == false) {
  50.    
  51.         cout << "非質數" << endl;  
  52.     }
  53.   }//end while
  54.  
  55. return 0;
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement