Gerg is having a party, and he has invited his friends. p of them have arrived already, but a are running late. To occupy his guests, he tried playing some team games with them, but he found that it was impossible to divide the p guests into any number of equal-sized groups of more than one person.
Luckily, he has a backup plan — a cake that he would like to share between his friends. The cake is in the shape of a square, and Gerg insists on cutting it up into equal-sized square pieces. He wants to reserve one slice for each of the a missing friends, and the rest of the slices have to be divided evenly between the p remaining guests. He does not want any cake himself. Can he do it?
Input
The input will consist of several test cases. Each test case will be given as a non-negative integer a and a positive integer p as specified above, on a line. Both a and p will fit into a 32-bit signed integer. The last line will contain ‘-1 -1’ and should not be processed.
Output
For each test case, output ‘Yes’ if the cake can be fairly divided and ‘No’ otherwise.
Sample Input
1 3
1024 17
2 101
0 1
-1 -1
Sample Output
Yes
Yes
No
Yes
问题链接:UVA10831 Gerg's Cake
问题简述:
给定a, p,问是否存在x^2 % p = a的解。
问题分析:
这是一个数学计算问题,求勒让德记号,需要计算快速幂。
题记:把功能封装到函数是一个好主意。
参考链接:(略)
AC的C++语言程序如下:
/* UVA10831 Gerg's Cake */
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
// 快速幂
ULL powmod(ULL x, ULL n, ULL m)
{
ULL result = 1;
for(; n; n>>=1) {
if(n & 1) {
result *= x;
result %= m;
}
x *= x;
x %= m;
}
return result;
}
int legendre (ULL x, ULL p)
{
x %= p;
return (!x || powmod(x, (p - 1) / 2, p) ==1);
}
int main()
{
int a, p;
while(~scanf("%d%d", &a, &p) &&(a != -1 || p != -1)) {
printf("%s\n", legendre(a, p) ? "Yes" : "No");
}
return 0;
}