快速幂-poj3641

来源:互联网 发布:pip linux 编辑:程序博客网 时间:2024/05/17 00:18
Language:
Pseudoprime numbers
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 5886 Accepted: 2345

Description

Fermat's theorem states that for any prime number p and for any integer a > 1, ap = a (mod p). That is, if we raise a to the pth power and divide by p, the remainder is a. Some (but not very many) non-prime values of p, known as base-a pseudoprimes, have this property for some a. (And some, known as Carmichael Numbers, are base-a pseudoprimes for all a.)

Given 2 < p ≤ 1000000000 and 1 < a < p, determine whether or not p is a base-a pseudoprime.

Input

Input contains several test cases followed by a line containing "0 0". Each test case consists of a line containing p and a.

Output

For each test case, output "yes" if p is a base-a pseudoprime; otherwise output "no".

Sample Input

3 210 3341 2341 31105 21105 30 0

Sample Output

nonoyesnoyesyes题意;求a的p次方对p取余是否等于a,p是合数。
#include<iostream>#include<set>#include<map>#include<vector>#include<queue>#include<cmath>#include<climits>#include<cstdio>#include<string>#include<cstring>#include<algorithm>typedef long long LL;using namespace std;bool is_prime(LL p){    if(p==1)        return false;    LL k=sqrt(double(p));    int i;    for(i=2; i<=k; i++)        if(p%i==0)            return false;    return true;}LL mod_pow(LL a,LL n,LL mod){    LL ans=1;    while(n>0)    {        if(n&1) ans=(ans*a)%mod;        a=a*a%mod;        n>>=1;    }    return ans;}int main(){    //freopen("in.txt","r",stdin);    LL p,a;    while(cin>>p>>a,p&&a)    {        if(is_prime(p))        {            cout<<"no"<<endl;            continue;        }        LL ans=mod_pow(a,p,p);        if((ans%p)==(a%p))            cout<<"yes"<<endl;        else            cout<<"no"<<endl;    }}



原创粉丝点击