[noip 2012] 同余方程

来源:互联网 发布:销售数据分析方法视频 编辑:程序博客网 时间:2024/06/05 09:32

大家都用 exgcd 之类的东西搞一点意思都没有。


我来讲讲自己的想法吧,
gcd(a, b) = 1
a^phi(b) = 1 (mod b)
x = a^(phi(b)-1) (mod b)

exgcd这么蛋疼东西我才不会呢!


#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <ctime>#include <vector>#include <utility>#include <stack>#include <queue>#include <iostream>#include <algorithm>template<class Num>void read(Num &x){    char c; int flag = 1;    while((c = getchar()) < '0' || c > '9')        if(c == '-') flag *= -1;    x = c - '0';    while((c = getchar()) >= '0' && c <= '9')        x = (x<<3) + (x<<1) + (c-'0');    x *= flag;    return;}template<class Num>void write(Num x){    if(!x) {putchar('0');return;}    if(x < 0) putchar('-'), x = -x;    static char s[20];int sl = 0;    while(x) s[sl++] = x%10 + '0',x /= 10;    while(sl) putchar(s[--sl]);}long long a, b, phi;long long power_mod(long long x,int k){    long long r = 1;    while(k)    {        if(k&1) r *= x, r %= b;        x *= x, x %= b, k >>= 1;    }    return r;}int main(){    long long  t;    read(a), read(b);    t = phi = b;    for(int i = 2; i * i <= b; i++)    {        if(!(t % i))        {            phi /= i, phi *= i - 1;            while(!(t % i)) t /= i;        }    }    if(t != 1) phi /= t, phi *= t - 1;    write(power_mod(a, phi - 1));    return 0;}
0 0
原创粉丝点击