Pseudoprime numbers POJ - 3641(快速幂+判素数)
題意:
給你兩個數,p和a;滿足兩個條件:
1.p不是素數;
2.apa^{p}ap %p==a;
滿足則輸出yes,反之輸出no。
題目:
Fermat’s theorem states that for any prime number p and for any integer a > 1, apa^{p}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
分析:
這道題一旦題意出來了,其他就是常規(guī)操作,第一個條件p為非素數很容易看出,但第二個條件,恕我眼拙,題目給了一個【a > 1, apa^{p}ap = a (mod p). 】的條件,我很容易就想到了費馬小定理的xp?1≡1(modp)x^{p-1}\equiv 1(mod p)xp?1≡1(modp),然后就掉進坑里爬都爬不起來,看到博客上的題意,心情很崩潰。
AC代碼:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; typedef long long ll; ll p,a; bool prime(ll x){int k=0;for(int i=2;i*i<=x;i++)if(x%i==0)k++;if(k==0) return true;return false; } ll mod(ll a,ll p,ll mod){ll ans=1;a%=mod;while(p){if(p&1) ans=a*ans%mod;p>>=1;a=a*a%mod;}return ans; } int main(){while(~scanf("%lld%lld",&p,&a)){if(!p&&!a)break;if(prime(p)){printf("no\n");continue;}if(mod(a,p,p)==a) printf("yes\n");else printf("no\n");}return 0; }總結
以上是生活随笔為你收集整理的Pseudoprime numbers POJ - 3641(快速幂+判素数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何打印指定页码如何打印电脑页码
- 下一篇: The Water Bowls POJ