ZOJ 1489

来源:互联网 发布:sql for in 循环语句 编辑:程序博客网 时间:2024/06/06 06:59

题解:

当n为偶数或者1时显然无解(BSGS过程可证)

除此之外2与n互质, 则必存在2^phi(n) = 1, 必有解

且最小解应该是phi(n)的最小约数x满足2^x % n = 1;

质因子拆分 + 快速幂判断就可

CODE: 

#include <iostream>#include <cstdio>using namespace std;int FastPowMod(int a, int b, int p){    int ret = 1 % p;    while(b){        if(b & 1) ret = ret * a % p;        a = a * a % p;        b >>= 1;    }    return ret;}int getPhi(int x){    int ret = x;    for(int i = 2; i * i <= x; ++i){        if(x % i == 0){            while(x % i == 0) x /= i;            ret = ret / i * (i - 1);        }    }    if(x > 1) ret = ret / x * (x - 1);    return ret;}int cal(int b, int x, int p){    int m = x;    for(int i = 2; i * i <= x; ++i){        if(x % i == 0){            while(x % i == 0) x /= i;            while(m % i == 0 && FastPowMod(b, m / i, p) == 1) m /= i;        }    }    if(x > 1){        while(m % x == 0 && FastPowMod(b, m / x, p) == 1) m /= x;    }    return m;}int solve(int x){    if(x % 2 == 0 || x == 1) return -1;    int phi = getPhi(x);    return cal(2, phi, x);}int main(){    int n;   // freopen("in.txt", "r", stdin);    while(cin >> n){        int res = solve(n);        if(~res) cout << "2^" << res << " mod " << n << " = 1" << endl;        else cout << "2^?" << " mod " << n << " = 1" << endl;    }    return 0;}

0 0