Pseudoprime numbers
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8682 | Accepted: 3645 |
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 2 10 3 341 2 341 3 1105 2 1105 3 0 0
Sample Output
no no yes no yes yes
Source
Waterloo Local Contest, 2007.9.23
题目分析:主要在于素数的判断和快速幂算法
1 #include <iostream> 2 using namespace std; 3 4 int prime(long long a) 5 { 6 int i; 7 if(a == 2) 8 return 1; 9 for(i = 2; i*i<=a; i++) 10 if(a%i == 0) 11 return 0; 12 return 1; 13 } 14 15 long long mod(long long a,long long b,long long c) 16 { 17 long long ans = 1; 18 a=a%c; 19 while(b>0) 20 { 21 if(b%2==1) ans=(ans*a)%c; 22 b=b/2; 23 a=(a*a)%c; 24 } 25 return ans; 26 } 27 int main() 28 { 29 long long a,p; 30 31 while(cin >> p >> a) 32 { 33 if(p==0 && a==0) break; 34 long long ans; 35 if(prime(p)) 36 cout << "no" << endl; 37 else 38 { 39 ans = mod(a,p,p); 40 if(ans == a) 41 cout << "yes" << endl; 42 else 43 cout << "no" << endl; 44 } 45 } 46 47 return 0; 48 }