Couple doubi
Problem Description
DouBiXp has a girlfriend named DouBiNan.One day they felt very boring and decided to play some games. The rule of this game is as following. There are k balls on the desk. Every ball has a value and the value of ith (i=1,2,...,k) ball is 1^i+2^i+...+(p-1)^i (mod p). Number p is a prime number that is chosen by DouBiXp and his girlfriend. And then they take balls in turn and DouBiNan first. After all the balls are token, they compare the sum of values with the other ,and the person who get larger sum will win the game. You should print “YES” if DouBiNan will win the game. Otherwise you should print “NO”.
Input
Multiply Test Cases.
In the first line there are two Integers k and p(1<k,p<2^31).
Output
For each line, output an integer, as described above.
Sample Input
2 3 20 3
Sample Output
YES
NO
思路:用费马小定理证明。
费马小定理是数论中的一个重要定理,其内容为: 假如p是质数,且(a,p)=1,那么 a^(p-1) ≡1(mod p)。即:假如a是整数,p是质数,且a,p互质(即两者只有一个公约数1),那么a的(p-1)次方除以p的余数恒等于1。
当k/(p-1)是整数时,即i^k可以写成i^(k/p-1)^p-1的形式时,可使用费马小定理。i^(k/p-1)可以看出定理中的a,因为p是素数,所以a和p肯定互质,满足条件。所以,1^i+2^i+...+(p-1)^i(mod p)=p-1;同样的意思,k就是(p-1)的倍数时,球的价值都为p-1。所以判断有几个这样的球,k/(p-1)是奇数时,DouBiNan肯定多拿一次,所以肯定获胜,而偶数时,双方拿的次数一样多。
当k/(p-1)是不是整数时,即i^k不可以写成i^(k/p-1)^p-1的形式,所以不可使用费马小定理。设原根g^i=i;i^k=g^(i*k);所以1^k+2^k+...+(p-1)^k=g^(1*m)+g^(2*m)+...+g^((p-i)*m),利用等比数列,原式等于((g^m)^p-g^m)/g^m-1;又因为(g^m)^p(mod p)=g^m,而g^m(mod p)=g^m,所以分子等于g^m-g^m=0;所以原式等于0。
综合上述两种情况,只需判断k/(p-1)是否为奇数即可,是则胜利,否则平局。
代码如下:
#include<stdio.h>
int main()
{ int k,p;
while(scanf("%d%d",&k,&p)!=EOF)
{
k=k/(p-1);
if(k&1)
printf("YES\n");
else printf("NO\n");
}
return 0;
}