Pseudoprime numbers
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 14334 Accepted: 6215
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
题目大概意思:
给出两个整数 ,判断 是否是 . 是 ,当且仅当 是合数且 .
分析:
由于 最大只会取到 ,故可以采用朴素的素数判定方法在 的时间复杂度内判断 是否为合数,且我们可以提前利用素数筛得到 以内的素数,以减少素数判定时考虑的因子个数。随后我们只需要计算 ,由于 较大,需要采用快速幂运算,这样可以在 的时间复杂度内计算出 .
下面贴代码:
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long ll;
const int MAX_N = 32000;
bool ispr[MAX_N];
int primes[MAX_N];
int pcnt;
void getprime(const int N);
bool is_prime(int x);
ll mod_pow(ll x, ll p, ll m);
int main()
{
getprime(MAX_N);
int a, p;
while (~scanf("%d%d", &p, &a) && a && p)
{
if (is_prime(p) || mod_pow(a, p, p) != a)
{
printf("no\n");
}
else
{
printf("yes\n");
}
}
return 0;
}
ll mod_pow(ll x, ll p, ll m)
{
ll res = 1;
while (p)
{
if (p & 1)
{
res = res * x % m;
}
x = x * x % m;
p >>= 1;
}
return res;
}
void getprime(const int N)
{
for (int i = 2; i < N; ++i)
{
if (!ispr[i])
{
primes[pcnt++] = i;
for (int j = i << 1; j < N; j += i)
{
ispr[j] = true;
}
}
}
}
bool is_prime(int x)
{
int sqx = sqrt((double)x) + 1;
for (int i = 0; primes[i] < sqx; ++i)
{
if (!(x % primes[i]))
{
return false;
}
}
return true;
}