HDU2138 随机素数测试 Miller-Rabin算法
題目描述
? Give you a lot of positive integers, just to find out how many prime numbers there are..
? In each case, there is an integer N representing the number of integers to find. Each integer won’t exceed 32-bit signed integer, and each of them won’t be less than 2.
? 32-bit signed intege,最普通的肯定要超時(shí),篩選法要超內(nèi)存,開(kāi)小的話就越界。
miller_rabin算法?
一.費(fèi)馬小定里
if n is prime and gcd(a,n) equals one ,then a^(n-1) = 1 (mod n)
費(fèi)馬小定理只是個(gè)必要條件,符合費(fèi)馬小定理而非素?cái)?shù)的數(shù)叫做Carmichael.
前3個(gè)Carmichael數(shù)是561,1105,1729。
Carmichael數(shù)是非常少的。
在1~100000000范圍內(nèi)的整數(shù)中,只有255個(gè)Carmichael數(shù)。
為此又有二次探測(cè)定理,以確保該數(shù)為素?cái)?shù):
二.二次探測(cè)定理
二次探測(cè)定理 如果p是一個(gè)素?cái)?shù),0<x<p,則方程x^2≡1(mod p)的解為x=1,p-1
根據(jù)以上兩個(gè)定理,如到Miller-Rabin算法的一般步驟:
0、先計(jì)算出m、j,使得n-1=m*2^j,其中m是正奇數(shù),j是非負(fù)整數(shù)
1、隨機(jī)取一個(gè)b,2<=b
2、計(jì)算v=b^m mod n
3、如果v==1,通過(guò)測(cè)試,返回
4、令i=1
5、如果v=n-1,通過(guò)測(cè)試,返回
6、如果i==j,非素?cái)?shù),結(jié)束
7、v=v^2 mod n,i=i+1
8、循環(huán)到5
說(shuō)明:
Miller-Rabin是隨機(jī)算法
得到的結(jié)果的正確率為75%,所以應(yīng)該多次調(diào)用該函數(shù),使正確概率提高為1-(1/4)^s
解云鵬你懂了嗎?
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <iostream> #include <algorithm>#define ll long long using namespace std; const int INF = 0x3f3f3f3f; int i, j, k; ll m, b; int numCase; ll n; bool flag; int S = 5; ll quickpow(ll m,ll n,ll k){int b = 1;while (n > 0){if (n & 1)b = (b*m)%k;n = n >> 1 ;m = (m*m)%k;}return b; }bool Miller_Rabin(){int temp_n = n -1;j = 0;while(temp_n % 2 == 0){++j;temp_n /= 2;}m = (n -1) / (1 << j);int v = quickpow(b, m, n);if(1 == v){flag = true;return flag;}int i = 0;while(++i <= 5){if(v == n - 1){flag = true;} else if(i == j){flag = false;return flag;}} }bool witness(ll a,ll n){ll t,d,x;d=1;int i=ceil(log(n-1.0)/log(2.0)) - 1;for(;i>=0;i--)//快速冪操作{x=d; d=(d*d)%n;if(d==1 && x!=1 && x!=n-1) return true;//二次探測(cè)法檢測(cè)if( ((n-1) & (1<<i)) > 0)d=(d*a)%n;}return d==1? false : true; } bool miller_rabin(ll n){int s[]={2,7,61};if(n==2) return true;if(n==1 || ((n&1)==0)) return false;for(int i=0;i<3;i++)if(witness(s[i], n)) return false;return true; }int main(){while(EOF != scanf("%d",&numCase)){flag = false;int count = 0;while(numCase--){cin >> n;if(miller_rabin(n)) ++count;}cout << count << endl;}return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/wushuaiyi/p/3879149.html
總結(jié)
以上是生活随笔為你收集整理的HDU2138 随机素数测试 Miller-Rabin算法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php外联样式,css外联样式不起作用怎
- 下一篇: ES6笔记 -- 变量/语句声明