Pollard_rho算法+Miller_Rabin算法(大素数的判断与素因子分解)(模板)
生活随笔
收集整理的這篇文章主要介紹了
Pollard_rho算法+Miller_Rabin算法(大素数的判断与素因子分解)(模板)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
const int S=20;//隨機算法判定次數,S越大,判錯概率越小
//計算 (a*b)%c. a,b都是long long的數,直接相乘可能溢出的
// a,b,c <2^63
LL mult_mod(LL a,LL b,LL c)
{a%=c;b%=c;LL ans=0;while(b){if(b&1){ans+=a;ans%=c;}a<<=1;if(a>=c)a%=c;b>>=1;}return ans;
}
//計算 x^n %c
LL pow_mod(LL x,LL n,LL mod)//x^n%c
{if(n==1)return x%mod;x%=mod;LL temp=x;LL ans=1;while(n){if(n&1) ans=mult_mod(ans,temp,mod);temp=mult_mod(temp,temp,mod);n>>=1;}return ans;
}
//以a為基,n-1=x*2^t a^(n-1)=1(mod n) 驗證n是不是合數
//一定是合數返回true,不一定返回false
bool check(LL a,LL n,LL x,LL t)
{LL ret=pow_mod(a,x,n);LL last=ret;for(int i=1;i<=t;i++){ret=mult_mod(ret,ret,n);if(ret==1&&last!=1&&last!=n-1) return true;//合數last=ret;}if(ret!=1) return true;return false;
}
// Miller_Rabin()算法素數判定
//是素數返回true.(可能是偽素數,但概率極小)
//合數返回false;
bool Miller_Rabin(LL n)
{if(n<2)return false;if(n==2)return true;if((n&1)==0) return false;//偶數LL x=n-1;LL t=0;while((x&1)==0){x>>=1;t++;}for(int i=0;i<S;i++){LL a=rand()%(n-1)+1;//rand()需要stdlib.h頭文件if(check(a,n,x,t))return false;//合數}return true;
}
//************************************************
//pollard_rho 算法進行質因數分解
//************************************************
LL ans[100];//質因數分解結果(剛返回時是無序的)
int cnt;//質因數的個數。數組小標從0開始LL gcd(LL a,LL b)
{if(a==0)return 1;//???????if(a<0) return gcd(-a,b);while(b){LL t=a%b;a=b;b=t;}return a;
}LL Pollard_rho(LL x,LL c)
{LL i=1,k=2;LL x0=rand()%x;LL y=x0;while(1){i++;x0=(mult_mod(x0,x0,x)+c)%x;LL d=gcd(y-x0,x);if(d!=1&&d!=x) return d;if(y==x0) return x;if(i==k){y=x0;k+=k;}}
}
//對n進行素因子分解
void findfac(LL n)
{if(Miller_Rabin(n))//素數{ans[cnt++]=n;return;}LL p=n;while(p>=n)p=Pollard_rho(p,rand()%(n-1)+1);findfac(p);findfac(n/p);
}
?
總結
以上是生活随笔為你收集整理的Pollard_rho算法+Miller_Rabin算法(大素数的判断与素因子分解)(模板)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ - 2115 C Looooop
- 下一篇: 2018宁夏邀请赛 - Goldbach