【快速幂】POJ3641

 输入a和p。如果p不是素数,则若满足ap = a (mod p)输出yes,不满足或者p为素数输出no。最简单的快速幂,啥也不说了。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 using namespace std;
 6 typedef long long ll;
 7 ll p,a; 
 8 
 9 int whether(int p)
10 {
11     int f=1;
12     for (int i=2;i*i<=p;i++)
13         if (p%i==0)
14         {
15             f=0;
16             break;
17         }
18     return f;
19 }
20 
21 int submain()
22 {
23     ll res=1,n=p,x=a;
24     while (n>0)
25     {
26         if (n&1) res=res * x % p;
27         /*如果n最后一位是一,那么乘上x*/
28         x=x*x % p;
29         n>>=1;
30         /*右移以为,即除以二*/
31     }
32     return (res==a);
33 }
34 
35 int main()
36 {
37     while (scanf("%lld%lld",&p,&a))
38     {
39         if (p==a && a==0) break;
40         if (!whether(p))
41         {
42             if (submain()) cout<<"yes"<<endl;
43                 else cout<<"no"<<endl;
44         }
45         else
46             cout<<"no"<<endl;
47     } 
48     return 0;
49 }
原文地址:https://www.cnblogs.com/iiyiyi/p/4811786.html