Prime Test
Time Limit: 6000MS | Memory Limit: 65536K | |
Total Submissions: 27513 | Accepted: 6874 | |
Case Time Limit: 4000MS |
Description
Given a big integer number, you are required to find out whether it's a prime number.
Input
The first line contains the number of test cases T (1 <= T <= 20 ), then the following T lines each contains an integer number N (2 <= N < 2
54).
Output
For each test case, if N is a prime number, output a line containing the word "Prime", otherwise, output a line containing the smallest prime factor of N.
Sample Input
2 5 10
Sample Output
Prime 2
题意:给出一个整数N(2 <= N < 254),判断N是否为素数。
思路:用到miller_rabin的素数判断和pollard_rho的整数分解,详见《算法导论》第31章第31.8至31.9节
以下是网上找的代码:
#include <iostream> #include <cmath> #include <cstdlib> #include <cstring> #include <cstdio> #include <queue> #include <ctime> #define ll __int64 using namespace std; const ll INF = pow(2.0, 60); const int TIME = 12; ll minf; ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll mod_mult(ll a, ll b, ll n) //计算(a*b)%n { ll ret = 0; a %= n; while(b) { if(b & 1) { ret += a; if(ret >= n) ret -= n; } a <<= 1; if(a >= n) a -= n; b >>= 1; } return ret; } ll mod_exp(ll a, ll b, ll n) //计算(a^b)%n { ll r = 1; a %= n; while(b) { if(b & 1) r = mod_mult(r, a, n); a = mod_mult(a, a, n); b >>= 1; } return r; } bool Witess(ll a, ll n) //以a为基对n进行Miller测试并实现二次探测 { ll m, x, y; int i, j = 0; m = n - 1; while(m % 2 == 0) { m >>= 1; j++; } x = mod_exp(a, m, n); for(i = 1; i <= j; i++) { y = mod_exp(x, 2, n); if(y == 1 && x != 1 && x != n - 1) //二次探测 return true; x = y; } if(y != 1) return true; return false; } bool miller_rabin(int times,ll n) { ll a; if(n == 1) return false; if(n == 2) return true; if(n % 2 == 0) return false; srand(time(NULL)); for(int i = 1; i <= times; i++) { a = rand() % (n - 1) + 1; if(Witess(a, n)) return false; } return true; } ll pollard_rho(ll n, int c) { ll i = 1, k = 2, x, y, d; srand(time(NULL)); x = rand() % n; y = x; while(true) { i++; x = (mod_mult(x, x, n) + c) % n; d = gcd(y - x, n); if(d > 1 && d < n) return d; if(y == x) return n; if(i == k) { y = x; k <<= 1; } } } void get_small(ll n, int c) { ll m; if(n == 1) return; if(miller_rabin(TIME, n)) { if(n < minf) minf = n; return; } m = n; while(m == n) m = pollard_rho(n, c--); get_small(m, c); get_small(n / m, c); } int main() { int t; ll n; scanf("%d", &t); while(t--) { minf = INF; scanf("%I64d", &n); if(miller_rabin(TIME, n)) printf("Prime\n"); else { get_small(n, 240); printf("%I64d\n", minf); } } return 0; }