参考博客:::https://blog.csdn.net/java_c_android/article/details/55802041
挑战程序设计竞赛 122页
Carmichael Numbers
时间限制: 1 Sec 内存限制: 64 MB提交: 16 解决: 7
[ 提交][ 状态 ][ 讨论版]
题目描述
Certain cryptographic algorithms make use of big prime numbers. However, checking whether a big number is prime is not so easy. Randomized primality tests exist that offer a high degree of confidence of accurate determination at low cost, such as the Fermat test. Let a be a random number between 2 and n - 1, where n is the number whose primality we are testing. Then, n is probably prime if the following equation holds: an mod n = a If a number passes the Fermat test several times, then it is prime with a high probability. Unfortunately, there is bad news. Certain composite numbers (non-primes) still pass the Fermat test with every number smaller than themselves. These numbers are called Carmichael numbers. Write a program to test whether a given integer is a Carmichael number.
输入
The input will consist of a series of lines, each containing a small positive number n ( 2 < n < 65, 000). A number n = 0 will mark the end of the input, and must not be processed.
输出
For each number in the input, print whether it is a Carmichael number or not as shown in the sample output
样例输入
1729 17 561 1109 431 0
样例输出
The number 1729 is a Carmichael number. 17 is normal. The number 561 is a Carmichael number. 1109 is normal. 431 is normal.
提示
来源
HOMEBack
题目大意:
我们把对任意的1<x<n都有x^n=x mod n成立的合数n称为Carmichael number,给定一个整数n,判断它是不是Carmichael number。
思路:
编译器暂时改为Dev c++ 原来是VS2012 ,为了适应过几周的蓝桥杯编译环境。
直接枚举x用上快速幂即可。
还有要注意的是合数,素数就不是Carmichael number啦。
#include<cstdio>
#include<cstring>
typedef long long LL;
const int MAXN=65000+10;
bool primer[MAXN];
LL pow(LL x,LL n,LL mod) //x^n%mod
{
LL res=1;
while(n)
{
if( n & 1) res=res*x%mod;
x=x*x%mod;
n>>=1;
}
return res;
}
int main()
{
memset(primer,0,sizeof(primer));
for(int i=2;i*i<MAXN;i++)
{
if(!primer[i])
for(int j=i;j*i<MAXN;j++)
primer[i*j]=1;
}
int n;
while(scanf("%d",&n),n)
{
bool ok=true;
if(!primer[n])
ok=false;
if(ok)
for(LL i=2;i<n;i++)
{
LL temp=pow(i,n,n);
if(temp!=i)
{
ok=false;
break;
}
}
if(ok)
printf("The number %d is a Carmichael number.\n",n);
else
printf("%d is normal.\n",n);
}
return 0;
}