POJ:3641-Pseudoprime numbers(快速幂)

Pseudoprime numbers

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 11470 Accepted: 4947

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 ≤ 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


解题心得:

  1. 题意就是给你两个数a,b,如果a的b次方 mod p等于a,并且p不是素数那么输出yes,否则输出no
  2. 先素数筛选判断p是不是素数,然后一个快速幂模拟一下最后mod是否等于a就行了,其实就是一个费马小定理的逆命题否定判断,就这个题来说学没学过数论都很简单。

#include <algorithm>
#include <stdio.h>
using namespace std;
typedef long long ll;

ll mod_mult(ll x,ll y) {
    ll res = 1;
    ll p = y;
    while(y) {
        if(y&1)
            res = (res*x)%p;
        x = (x*x)%p;
        y >>= 1;
    }
    return res%p;
}

bool checke_prim(int n) {
    for(int i=2;i*i<=n;i++)
        if(n % i == 0)
            return true;
    return false;
}

int main() {
    ll p,a;
    while(scanf("%lld%lld",&p,&a) && p|a) {
        bool flag = checke_prim(p);
        ll ans = mod_mult(a,p);
        if(ans == a && flag)
            printf("yes
");
        else
            printf("no
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/GoldenFingers/p/9107131.html