您的位置:首页 > 其它

3667: Rabin-Miller算法

2016-12-31 07:38 316 查看

3667: Rabin-Miller算法

Time Limit: 60 Sec  Memory Limit: 512 MB
Submit: 1247  Solved: 379

[Submit][Status][Discuss]

Description

Input

第一行:CAS,代表数据组数(不大于350),以下CAS行,每行一个数字,保证在64位长整形范围内,并且没有负数。你需要对于每个数字:第一,检验是否是质数,是质数就输出Prime 

第二,如果不是质数,输出它最大的质因子是哪个。 

Output

第一行CAS(CAS<=350,代表测试数据的组数) 

以下CAS行:每行一个数字,保证是在64位长整形范围内的正数。 

对于每组测试数据:输出Prime,代表它是质数,或者输出它最大的质因子,代表它是和数 

Sample Input

6

2

13

134

8897

1234567654321

1000000000000

Sample Output

Prime

Prime

67

41

4649

5

HINT

数据范围: 

保证cas<=350,保证所有数字均在64位长整形范围内。 

Source



[Submit][Status][Discuss]


用Miller-Rabin算法判断是不是质数,Pollard-Rho算法分解因子,以及得用O(1)的快速乘。

基本是模板了,,留点笔记吧。



最后是O(1)的快速乘了,,虽然不知道为什么可以,,不过背下来就好吧。。

据说不推荐对大模数使用#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
#include<cmath>
using namespace std;

typedef unsigned long long LL;
typedef long long ll;

int T,tot;
LL N,pri[120];

LL gcd(LL x,LL y) {return !y?x:gcd(y,x%y);}

ll Mul(ll a,ll b,ll p){
ll d=((long double)a/p*b+1e-8);
ll res=a*b-d*p;
res=res<0?res+p:res;
return res;
}

/*LL Mul(LL x,LL y,LL p)
{
if (x < y) swap(x,y);
LL ret = 0;
for (; y; y >>= 1LL)
{
if (y&1) ret += x,ret %= p;
x = (x + x) % p;
}
return ret;
}*/

LL ksm(LL x,LL y,LL p)
{
LL ret = 1;
for (; y; y >>= 1LL)
{
if (y&1) ret = Mul(ret,x,p);
x = Mul(x,x,p);
}
return ret;
}

bool Miller_Rabin(LL n)
{
if (n == 2) return 1;
if (n < 2 || !(n&1)) return 0;
LL m = n - 1,k = 0;
while (!(m&1)) m >>= 1LL,++k;
for (int I = 0; I < 5; I++)
{
LL rd = rand() % (n-1) + 1;
LL x = ksm(rd,m,n);
for (int j = 0; j < k; j++)
{
LL y = Mul(x,x,n);
if (y == 1 && x != 1 && x != n - 1) return 0;
x = y;
}
if (x != 1) return 0;
}
return 1;
}

LL Pollard_Rho(LL n,LL c)
{
LL x,y; int ti,k; ti = 1; k = 2;
x = y = rand() % (n-1) + 1;
for (;;)
{
++ti; x = Mul(x,x,n) + c; x %= n;
if (x == y) return n;
LL now = (long long)(y) - (long long)(x) + (long long)(n);
now %= n; LL g = gcd(now,n);
if (1 < g && g < n) return g;
if (ti == k) y = x,k <<= 1;
}
}

void find(LL n,int c)
{
if (n == 1) return;
if (Miller_Rabin(n))
{
pri[++tot] = n;
return;
}
LL p = n; int k = c;
while (p >= n) p = Pollard_Rho(p,c--);
find(p,k); find(n / p,k);
}

LL getLL()
{
char ch = getchar(); LL ret = 0;
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9')
ret = ret*10LL + 1LL*(ch - '0'),ch = getchar();
return ret;
}

int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif

cin >> T;
while (T--)
{
N = getLL(); tot = 0; find(N,120);
sort(pri + 1,pri + tot + 1);
if (pri[tot] == N) puts("Prime");
else printf("%lld\n",pri[tot]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: