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 ...
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 2 10 3 341 2 341 3 1105 2 1105 3 0 0
Sample Output
no no yes no yes yes
本題用到快速冪,素數判定、二者結合;
題意:輸入兩個數p,a.先判斷p是否為素數,如果是,輸出no。否則,再判斷a的p次方取餘p是否為a,是則yes,反之
則no。
#include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
typedef long long ll;
int isprime(ll n)
{
if(n<=3) return n>1;
int k;
k=sqrt(n);
if(n%6!= 1 && n%6!=5)
return 0;
for(int i=5;i<=k;i+=6)
{
if(n%i==0 || n%(i+2)==0)
return 0;
}
return 1;
}
ll qpow(ll a, ll n,ll mod)//計算a^n % mod
{
ll re = 1;
while(n)
{
if(n & 1)//判斷n的最後一位是否為1
re = (re * a) % mod;
n >>= 1;//捨去n的最後一位
a = (a * a) % mod;//將a平方
}
return re;
}
int main()
{
ll p,a;
while(cin>>p>>a&&a&&p)
{
if(isprime(p))
cout<<"no"<<endl;
else
{
if(a==qpow(a,p,p))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
return 0;
}
typedef
typedef long long ll;
快速冪模板
ll qpow(ll a, ll n,ll mod)//計算a^n % mod
{
ll re = 1;
while(n)
{
if(n & 1)//判斷n的最後一位是否為1
re = (re * a) % mod;
n >>= 1;//捨去n的最後一位
a = (a * a) % mod;//將a平方
}
return re;
}
質數判定模板
int isprime(ll n)
{
if(n<=3) return n>1;
int k;
k=sqrt(n);
if(n%6!= 1 && n%6!=5)
return 0;
for(int i=5;i<=k;i+=6)
{
if(n%i==0 || n%(i+2)==0)
return 0;
}
return 1;
}
註意輸入用cin,用scanf會wa