日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HDU2138 随机素数测试 Miller-Rabin算法

發布時間:2023/12/10 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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,最普通的肯定要超時,篩選法要超內存,開小的話就越界。

miller_rabin算法?

一.費馬小定里

if n is prime and gcd(a,n) equals one ,then a^(n-1) = 1 (mod n)

費馬小定理只是個必要條件,符合費馬小定理而非素數的數叫做Carmichael.

前3個Carmichael數是561,1105,1729。

Carmichael數是非常少的。

在1~100000000范圍內的整數中,只有255個Carmichael數。

為此又有二次探測定理,以確保該數為素數:

二.二次探測定理

二次探測定理 如果p是一個素數,0<x<p,則方程x^2≡1(mod p)的解為x=1,p-1

根據以上兩個定理,如到Miller-Rabin算法的一般步驟:

0、先計算出m、j,使得n-1=m*2^j,其中m是正奇數,j是非負整數

1、隨機取一個b,2<=b

2、計算v=b^m mod n

3、如果v==1,通過測試,返回

4、令i=1

5、如果v=n-1,通過測試,返回

6、如果i==j,非素數,結束

7、v=v^2 mod n,i=i+1

8、循環到5

說明:

Miller-Rabin是隨機算法

得到的結果的正確率為75%,所以應該多次調用該函數,使正確概率提高為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;//二次探測法檢測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; }

?

轉載于:https://www.cnblogs.com/wushuaiyi/p/3879149.html

總結

以上是生活随笔為你收集整理的HDU2138 随机素数测试 Miller-Rabin算法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。