这是题目链接:
链接:https://ac.nowcoder.com/acm/contest/889/B
这题就是剩余定理模板题,慢慢学吧,我竟然不知道,比赛的时候还在默默地算,,,,,给你b,c
(x+y)%p = b,(x*y)%p = c,问你有没有解,误解就输出-1 -1,有就输出想x和y。
Amy asks Mr. B problem B. Please help Mr. B to solve the following problem.
Let p = 1000000007.
Given two integers b and c, please find two integers x and y(0 \leq x \leq y < p)(0≤x≤y<p), such that
(x + y) \bmod p = b(x+y)modp=b
(x \times y) \bmod p = c(x×y)modp=c
输入描述:
The first line contains an integer t, which is the number of test cases (1 <= t <= 10).
In the following t lines, each line contains two integers b and c (0 <= b, c < p).
输出描述:
For each test case, please output x, y in one line.
If there is a solution, because x <= y, the solution is unique.
If there is no solution, please output -1, -1
示例1
输入
复制
10
4 4
5 6
10 10
10 25
20000 100000000
0 5
3 6
220 284
0 1
1000000000 1000000000
输出
复制
2 2
2 3
-1 -1
5 5
10000 10000
474848249 525151758
352077071 647922939
448762649 551237578
-1 -1
366417496 633582504
这是AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod =1e9 + 7;
const int N = 1e5 + 5;
ll poww(ll a,ll b)
{
ll ret = 1;
while(b)
{
if(b&1)
{
ret = ret * a % mod;
}
a = a * a % mod;
b/=2;
}
return ret;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
ll b,c;
scanf("%lld%lld",&b,&c);
ll inv = poww(2,mod - 2);//求2的逆元
ll sum = ((b * b % mod - 4 * c % mod)%mod + mod)%mod;//(x-y)^2%mod
ll k = poww(sum,(mod+1)/4);//这个就是剩余定理,根据平方求出一个数poww(sum,(mod+1)/4);
ll x = ((b + k) * inv )%mod;
ll y = ((b - k) * inv)%mod;
y = (y + mod)%mod;//为了避免y是负数。
//cout << inv << " " << sum << " " << k << endl;
if(x > y)
{
swap(x,y);//前面是小的,后面是大的。
}
if((x+y)%mod == b && ((x)*(y)%mod) == c)//判断解是否合理
{
printf("%lld %lld\n",x,y);
}
else
{
printf("-1 -1\n");
}
}
}