Miller_Rabin算法(随机算法,判断一个数是否是素数)

Posted 一个人的时光

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Miller_Rabin算法(随机算法,判断一个数是否是素数)相关的知识,希望对你有一定的参考价值。

 1 const int S = 20;//随机算法判定次数,S越大,判错概率越小
 2 LL pow_mod(LL a, LL b, LL mod) { // a^b%mod
 3     LL ans = 1;
 4     a = a % mod;
 5     while(b) {
 6         if(b & 1) {
 7             ans = (ans * a) % mod;
 8         }
 9         a = ( a * a ) % mod;
10         b >>= 1;
11     }
12     return ans;
13 }
14 bool check(LL a, LL n, LL x, LL t) {
15     LL ret = pow_mod(a, x, n);
16     LL last = ret;
17     for(int i = 1; i <= t; i++) {
18         ret = (ret * ret) % n;
19         if(ret == 1 && last != 1 && last != n - 1) return true;
20         last = ret;
21     }
22     if(ret != 1) return true;
23     else return false;
24 }
25 bool Miller_Rabin(long long n) {
26     if(n < 2)return false;
27     if(n == 2) return true;
28     if( (n & 1) == 0) return false;
29     LL x = n - 1;
30     LL t = 0;
31     while( (x & 1) == 0 ) {
32         x >>= 1;
33         t++;
34     }
35     for(int i = 0; i < S; i++) {
36         LL a = rand() % (n - 1) + 1;
37         if(check(a, n, x, t))
38             return false;
39     }
40     return true;
41 }

 

以上是关于Miller_Rabin算法(随机算法,判断一个数是否是素数)的主要内容,如果未能解决你的问题,请参考以下文章

10^9以上素数判定,Miller_Rabin算法

随机素数测试(Miller_Rabin算法)和求整数素因子(Pollard_rho算法)

素数判定Miller_Rabin 算法详解

miller_rabin算法检测生成大素数的RSA算法实现

[模板] Miller_Rabin和Pollard_Rho

数论Miller_Rabin