hdu 3307

来源:互联网 发布:matlab牛顿迭代算法 编辑:程序博客网 时间:2024/05/21 20:22

题解

  1. a1moda0=y
    a2moda0=xy+y
    ….
  2. anmoda0=i=0n1xiy=y(xn1)/(x1)
  3. 若y / (x - 1) % a0 = 0答案为1, 否则n要满足(x^n - 1) mod t = 0
    t = a0 / gcd(a0, y / (x - 1))(扩展欧几里得可证)
    即x^n mod t = 1
  4. 若gcd(x, t) != 1无解, 否则必存在xϕ(t)=1(modt)
    此时对phi(t)分解因子找最小的k满足x^k % t = 1就可.

code:

#include <iostream>#include <cstdio>using namespace std;typedef long long ll;ll x, y, a0;ll FastPowMod(ll a, ll b, ll p){    ll ret = 1 % p;    while(b){        if(b & 1) ret = ret * a % p;        a = a * a % p;        b >>= 1;    }    return ret;}ll getPhi(ll x){    ll ret = x;    for(ll i = 2; i * i <= x; ++i)        if(x % i == 0){            while(x % i== 0) x /= i;           ret -= ret / i;        }    if(x > 1) ret -= ret / x;    return ret;}ll cal(ll x, ll t){    ll p = getPhi(t);    ll tmp = p;    for(ll i = 2; i * i <= p; ++i){        if(p % i == 0){            while(p % i == 0) p /= i;            while(tmp % i == 0 && FastPowMod(x, tmp / i, t) == 1) tmp /= i;        }    }    if(p > 1){         while(tmp % p == 0 && FastPowMod(x, tmp / p, t) == 1) tmp /= p;    }    return tmp;}ll gcd(ll a, ll b) {return b == 0 ? a : gcd(b, a % b);}int main(){   // freopen("in.txt", "r", stdin);    while(cin >> x >> y >> a0){        y /= x - 1;        if(y % a0 == 0) {            cout << "1" << endl;            continue;        }        ll t = a0 / gcd(a0, y);        if(gcd(x, t) == 1){            cout << cal(x, t) << endl;            continue;        }        cout << "Impossible!" << endl;    }    return 0;}
0 0
原创粉丝点击