Description
给定一个n , 我们把对任意的1<x<n都有 x^n=x mod n 成立的合数 n 称为good number。现求该数是否为good number。
Input
输入一个数 n (n<1000000)
Output
输出YES或NO
Sample Input
561
21
Sample Output
YES
NO
解析
1. 首先若输入n,n为质数则直接输出NO
2. 通过条件 x^n = x mod n 联想到快速幂取模
代码
#include<stdio.h>
#include<string.h>
#define MAX 1000005
typedef long long LL;
int num[MAX],n;
void select()
{
int i,j;
for(i=2;i<=MAX;i++)
{
for(j=i*2;j<=MAX;j+=i)
{
num[j]=1;
}
}
}
LL quick_pow(LL x,LL c)
{
LL re=1;
while(c>0)
{
if(c%2==1)
re=re*x%n;
x=x*x%n;
c=c/2;
}
return re;
}
int main()
{
select();
while(~scanf("%d",&n))
{
int i,flag=1;
if(num[n]==0)
printf("NO\n");
else
{
for(i=2;i<n;i++)
{
if(quick_pow(i,n)!=i%n)
{
flag=0;
break;
}
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}