Advertisement
uopspop

Untitled

Apr 29th, 2016
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <vector>
  4. #include <cmath>
  5. #define maxn 46340  // sqrt(2147483647) < 46341
  6. using namespace std;
  7. bool c[maxn+10];  //0~46340之間false為質數
  8. vector <int> p;    // 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.   memset(c,0,sizeof(c));
  26.   c[0]=c[1]=1;
  27.   for(i=2;i<=maxn;++i)
  28.   {
  29.      if(c[i]==1) continue; //非質數
  30.      p.push_back(i);  // i是質數,放入 p 中
  31.      //是質數的倍數 註記為非質數
  32.      for(j=i+i; j<=maxn; j+=i)
  33.        c[j]=1;                  
  34.   }
  35.   //  for(k=2; k<=100; ++k)  // 印出 2~100的質數
  36. //    if( !c[k] ) cout << k << endl;
  37. //  cout << p.size() <<" " << p[p.size()-1] << endl;
  38.   return ;
  39. }
  40. // 主程式
  41. int main()
  42. {
  43.   sieve(); //建質數表,有bool c[] 及 vector <int> p
  44.   int n;
  45.   while( cin >> n )
  46.   {
  47.     bool final = isp(n);  
  48.     if (final == true) {
  49.         cout << "質數" << endl;        
  50.     } else if(final == false) {
  51.    
  52.         cout << "非質數" << endl;  
  53.     }
  54.   }//end while
  55.  
  56. return 0;
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement