Pseudoprime numbers

Pseudoprime numbers

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3408    Accepted Submission(s): 1586


Problem Description
Fermat's theorem states that for any prime number p and for any integer a > 1, a^p == 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 ≤ 1,000,000,000 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
 
先判断是否为素数,如果不是再进行快速幂取模.
 
 1 #include <bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 
 5 bool prim(ll x){
 6     bool flag = true;
 7     for(int i=2;i<=sqrt(x);i++){
 8         if(x%i==0){
 9             flag = false;
10             break;
11         }
12     }
13     return flag;
14 }
15 
16 ll pow(ll a,ll b,ll mod){
17     ll ret = 1;
18     while(a){
19         if(a&1){
20             ret = ret*b%mod;
21         }
22         b = b*b%mod;
23         a>>=1;
24     }
25     return ret%mod;
26 }
27 
28 ll n,m;
29 int main(){
30     while(cin>>n>>m&&!(n==0&&m==0)){
31         bool prime = prim(n);
32         if(!prime){
33             ll ans = pow(n,m,n);
34             if(ans==m){
35                 cout<<"yes"<<endl;
36             }else{
37                 cout<<"no"<<endl;
38             }
39         }else{
40             cout<<"no"<<endl;
41         }
42     }
43     return 0;
44 }

 

posted @ 2018-08-24 21:28  #忘乎所以#  阅读(109)  评论(0)    收藏  举报