pollard_rho和Miller_Rabin

时间:2023-03-09 17:15:01
pollard_rho和Miller_Rabin

Miller_Rabin就是以概论大小来判断素数 可以判断2^63范围的数

pollard_rho推荐两个很好的博客来理解:整数分解费马方法以及Pollard rho[ZZ]Pollard Rho算法思想

 //#pragma comment(linker, "/STACK:167772160")//手动扩栈~~~~hdu 用c++交
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<algorithm>
#include<vector>
#include<malloc.h>
using namespace std;
#define clc(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
#define LL long long
const double eps = 1e-;
const double pi = acos(-);
// inline int r(){
// int x=0,f=1;char ch=getchar();
// while(ch>'9'||ch<'0'){if(ch=='-') f=-1;ch=getchar();}
// while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
// return x*f;
// }
const int Times = ;
const int N = ; LL ct, cnt;
LL fac[N], num[N];//fac记录素因子,num记录每个因子的次数 LL gcd(LL a, LL b)
{
return b? gcd(b, a % b) : a;
}
//return a*b%m
LL multi(LL a, LL b, LL m)
{
LL ans = ;
a %= m;
while(b)
{
if(b & )
{
ans = (ans + a) % m;
b--;
}
b >>= ;
a = (a + a) % m;
}
return ans;
} LL quick_mod(LL a, LL b, LL m)
{
LL ans = ;
a %= m;
while(b)
{
if(b & )
{
ans = multi(ans, a, m);
b--;
}
b >>= ;
a = multi(a, a, m);
}
return ans;
}
//判断素数
bool Miller_Rabin(LL n)
{
if(n == ) return true;
if(n < || !(n & )) return false;
LL m = n - ;
int k = ;
while((m & ) == )
{
k++;
m >>= ;
}
for(int i=; i<Times; i++)
{
LL a = rand() % (n - ) + ;
LL x = quick_mod(a, m, n);
LL y = ;
for(int j=; j<k; j++)
{
y = multi(x, x, n);
if(y == && x != && x != n - ) return false;
x = y;
}
if(y != ) return false;
}
return true;
}
//分解素数
LL pollard_rho(LL n, LL c)
{
LL i = , k = ;
LL x = rand() % (n - ) + ;
LL y = x;
while(true)
{
i++;
x = (multi(x, x, n) + c) % n;
LL d = gcd((y - x + n) % n, n);
if( < d && d < n) return d;
if(y == x) return n;
if(i == k)
{
y = x;
k <<= ;
}
}
} void find(LL n, int c)
{
if(n == ) return;
if(Miller_Rabin(n))
{
fac[ct++] = n;
return ;
}
LL p = n;
LL k = c;
while(p >= n) p = pollard_rho(p, c--);
find(p, k);
find(n / p, k);
} int main()
{
LL n;
while(cin>>n)
{
ct = ;
find(n, );
sort(fac, fac + ct);
num[] = ;
int k = ;
for(int i=; i<ct; i++)
{
if(fac[i] == fac[i-])
++num[k-];
else
{
num[k] = ;
fac[k++] = fac[i];
}
}
cnt = k;
for(int i=; i<cnt; i++)
cout<<fac[i]<<"^"<<num[i]<<" ";
cout<<endl;
}
return ;
}