[2016-05-10][51nod][1106 质数检测]

  • 时间:2016-05-10 12:48:09 星期二

  • 题目编号:[2016-05-10][51nod][1106 质数检测]

  • 题目大意:给出N个正整数,检测每个数是否为质数。如果是,输出”Yes”,否则输出”No”。

  • 分析:

    1. 直接上模板
    2. 打sqrt(1E9)内的质数表,直接判断能否被所有质数整除即可
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. using namespace std;
  5. typedef long long ll;
  6. const int maxp = 31622 + 10;//sqrt(1E9)
  7. int pri[maxp];
  8. void inipri(){
  9. memset(pri,0,sizeof(pri));
  10. for(int i = 2 ; i < maxp ; ++i){
  11. if(!pri[i]) pri[++pri[0]] = i;
  12. for(int j = 1 ; j <= pri[0] && pri[j]*i < maxp;++j){
  13. pri[pri[j] * i] = 1;
  14. if(i % pri[j] == 0) break;
  15. }
  16. }
  17. }
  18. int main(){
  19. inipri();
  20. int n,a;
  21. scanf("%d",&n);
  22. for(int i = 0 ; i < n ; ++i){
  23. scanf("%d",&a);
  24. if((a & 1) == 0){
  25. puts(a == 2 ? "Yes" : "No");
  26. }else {
  27. int flg = 1;
  28. for(int j = 1; j < pri[0] && pri[j] * pri[j] < a;++j){
  29. if(a % pri[j] == 0){
  30. flg = 0;
  31. break;
  32. }
  33. }
  34. puts(flg ? "Yes" : "No");
  35. }
  36. }
  37. return 0;
  38. }
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. using namespace std;
  5. typedef long long ll;
  6. ll muilt_mod(ll a, ll b ,ll c){
  7. a %= c;
  8. b %= c;
  9. ll ret = 0;
  10. ll tmp = a;
  11. while(b){
  12. if(b & 1){
  13. ret += tmp;
  14. if(ret > c) ret -= c;
  15. }
  16. tmp <<= 1;
  17. if(tmp > c) tmp -= c;
  18. b >>= 1;
  19. }
  20. return ret;
  21. }
  22. ll pow_mod(ll a, ll n, ll mod){
  23. ll ret = 1;
  24. ll tmp = a % mod;
  25. while(n){
  26. if(n & 1) ret = muilt_mod(ret,tmp,mod);
  27. tmp = muilt_mod(tmp,tmp,mod);
  28. n >>= 1;
  29. }
  30. return ret;
  31. }
  32. bool check(ll a, ll n , ll x,ll t){
  33. ll ret = pow_mod(a,x,n);
  34. ll last = ret;
  35. for(int i = 1; i <= t; ++i){
  36. ret = muilt_mod(ret,ret,n);
  37. if(ret == 1 && last != 1 && last != n - 1) return true;
  38. last = ret;
  39. }
  40. if(ret != 1) return true;
  41. else return false;
  42. }
  43. bool Miller_Rabin(ll n){
  44. if(n < 2) return false;
  45. if(n == 2) return true;
  46. if((n & 1) == 0 ) return false;
  47. ll x = n - 1,t = 0;
  48. while((x & 1) == 0){
  49. x >>= 1;
  50. ++t;
  51. }
  52. srand(NULL);
  53. int S = 8;
  54. for(int i = 0 ; i < S;++i){
  55. ll a = rand() % (n - 1) + 1;
  56. if(check(a,n,x,t)) return false;
  57. }
  58. return true;
  59. }
  60. int main(){
  61. int n,a;
  62. scanf("%d",&n);
  63. for(int i = 0 ; i < n ; ++i){
  64. scanf("%d",&a);
  65. puts(Miller_Rabin(a)?"Yes":"No");
  66. }
  67. return 0;
  68. }


来自为知笔记(Wiz)


posted on 2016-05-10 13:16  红洋  阅读(180)  评论(0编辑  收藏  举报

导航