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
The title used fast power, primality, a combination of both;
that Italy: two input numbers p, a first determined whether p is a prime number, and if so, output no.. If not, then a judge of the p-th power modulo p whether it is a, is then yes, the contrary
is 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 (A LL, LL n, LL MOD) // calculate% MOD n ^ A {LL Re = 1 ; the while (n) { IF (n & 1) // determines whether the last bit of n is 1 = Re (Re * a)% MOD; = n >> . 1; // discarded last a n = a (a * a)% MOD; // to a squared } return Re;} int main () { P LL, A; the while (CIN >> >> P A A && && P) { IF (isPrime (P)) COUT << " NO " << endl; the else { IF (A == qpow (A, P, P)) << cout " yes " << endl;else cout<<"no"<<endl; } } return 0; }
typedef
typedef long long ll;
Fast power Templates
qpow LL (LL A, LL n, LL MOD) // calculate% MOD n ^ A
{
LL = Re . 1 ; the while (n) { IF (& n . 1) // determines whether the last bit of n is 1 re = (Re * a)% MOD; = n >> . 1; // discarded last a n = a (a * a)% MOD; // to a squared } return Re;
}
Prime number is determined template
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; }
Note input cin, with scanf will wa