平方剩余的问题,题目只要判断是否存在平方剩余就行啦。。
int solve(LL a, LL p) { //判断x*x (-=) a(mod p) 是否存在
LL res = pow_mod(a , (p - 1) >> 1, p);
if (res == p - 1)
return false;
return ture;
}
如果要求最小的解x,的话就要复杂一些
int modsqr(int a,int n)
{
int b,k,i,x;
if(n == 2) return a % n;
if(pow_mod(a,(n-1)/2,n) == 1)
{
if(n%4 == 3) x=pow_mod(a,(n+1)/4,n);
else
{
for(b=1;pow_mod(b,(n-1)/2,n) == 1 ; b++)
i=(n - 1)/2;
k=0;
do
{
i/=2;
k/=2;
if( (pow_mod(a,i,n)* (ll)pow_mod(b,k,n)+1)%n == 0 )
{
k+=(n-1)/2;
}
}
while(i%2 == 0);
x=(pow_mod(a,(i+1)/2,n)*(ll)pow_mod(b,k/2,n)) % n;
}
if(x*2 > n) x=n-x;
return x;
}
return -1;
}
不知道 为什么我用这个打答案错误。。但是上面的代码输出的x是正确的。。所以还是用了上面那个。
AC代码:
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
typedef long long ll;
ll pow_mod(ll a,ll b,ll c)
{
ll res=1;
while(b)
{
if(b&1) res=res*a%c;
a=a*a%c;
b>>=1;
}
return res;
}
int main()
{
int a,n,ant=1,ans,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&n);
ans=pow_mod(a,(n-1)/2,n);
printf("Scenario #%d:\n",ant++);
if(ans == n-1) printf("-1\n");
else printf("1\n");
printf("\n");
}
return 0;
}
路途。。。。