UVA - 374

https://vjudge.net/problem/19685/origin

费马小定理优化快速幂

因为加了费马小定理优化,小心2 2 2这种情况,会出现0 0 2,也就是0的0次方,实际答案为0

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#define inf 2147483647
#define N 47000
#define p(a) putchar(a)
#define For(i,a,b) for(long long i=a;i<=b;++i)

using namespace std;
long long T;
long long x,y,m,cnt;
long long prime[N];
bool vis[N];
void in(long long &x){
    long long y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(long long x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

long long ksm(long long a,long long b){
    long long r=1;
    while(b>0){
        if(b&1)
            r=r*a%m;
        a=a*a%m;
        b>>=1;
    }
    return r;
}

void Euler(){
    vis[1]=1;   
    For(i,2,N){
        if(!vis[i]) prime[++cnt]=i;
        for(long long j=1;j<=cnt&&i*prime[j]<=N;j++){
            vis[i*prime[j]]=1;
            if(i%prime[j]==0)
                break;
        }
    }
}

int main(){
    Euler();
    while(scanf("%lld%lld%lld",&x,&y,&m)!=EOF){       
        x%=m;
        if(!vis[m])
            y%=m-1;
        if(!x&&!y)
            y=1;
        o(ksm(x,y));p('\n');
    }     
    return 0;
}

 

posted @ 2019-08-02 00:15  WeiAR  阅读(98)  评论(0编辑  收藏  举报