Problem Description
Many problems require printing the probability of something. Moreover, it is common that if the answer is ab, you should output a×b−1(modp) (p is a prime number). In these problems, you cannot know the exact value of the probability. It’s so confusing!!! Now, we want to reverse engineer the exact probability from such calculated output value x. We do so by guessing the probability is the one with the minimum b such that a×b−1=x(modp). Now we invite you to solve this problem with us!
You are given two positive integers p and x, where p is a prime number.
Please find the smallest positive integer b such that there exist some positive integer a satisfying a<b and a≡bx(modp).
Input
The first line contains an integer T indicating there are T tests. Each test consists of a single line containing two integers: p,x.
-
1≤T≤2×105
-
3≤p≤1015
-
p is a prime
-
1<x<p
Output
For each test, output a line containing a string represents the fraction ab using the format “a/b” (without quotes).
Sample Input
3
11 7
998244353 554580197
998244353 998244352
Sample Output
2/5
8/9
499122176/499122177
- 题意
求解满足 a ≡ b x a \equiv\ bx a≡ bx(mod p),a<b,x<p,的b的最小解,输出a/b - 思路
把同余方程写成
a = b x − p y , ( y = ⌊ b x p ⌋ ) 0 < a < b ⇒ p x < b y < p x − 1 … 1 a=bx-py, (y=\lfloor {\frac{bx}{p} }\rfloor)\\ 0<a<b\\ \Rightarrow \frac{p}{x}<\frac{b}{y}<\frac{p}{x-1}\dots1 a=bx−py,(y=⌊pbx⌋)0<a<b⇒xp<yb<x−1p…1
显然对于这个不等式当 ⌊ p x ⌋ ! = ⌊ p x − 1 ⌋ \lfloor {\frac{p}{x} }\rfloor!=\lfloor {\frac{p}{x-1} }\rfloor ⌊xp⌋!=⌊x−1p⌋时,最小的b显然是 ⌊ p x ⌋ + 1 \lfloor {\frac{p}{x} }\rfloor+1 ⌊xp⌋+1此时 y = = 1 y==1 y==1。
当 ⌊ p x ⌋ = = ⌊ p x − 1 ⌋ \lfloor {\frac{p}{x} }\rfloor == \lfloor {\frac{p}{x-1} }\rfloor ⌊xp⌋==⌊x−1p⌋时我们可以进行如下操作
令 z = ⌊ p x ⌋ , x − 1 = k z=\lfloor {\frac{p}{x} }\rfloor,x-1=k z=⌊xp⌋,x−1=k于是
p x − z < b y − z < p k − z p − x z x < b − y z y < p − k z k \frac{p}{x}-z<\frac{b}{y}-z<\frac{p}{k}-z\\ \frac{p-xz}{x}<\frac{b-yz}{y}<\frac{p-kz}{k}\\ xp−z<yb−z<kp−zxp−xz<yb−yz<kp−kz
此时,不等式中的分数的分子小于分母,分子分母交换得 k p − k z < y b − y z < x p − x z … 2 \frac{k}{p-kz}<\frac{y}{b-yz}<\frac{x}{p-xz}\dots2 p−kzk<b−yzy<p−xzx…2
可以观察出1式和2式具有形式的一致性,联系辗转相除法,我们可以仿造辗转相除法的形式解出最小的b。 - 代码
#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int t;
ll p,x;
ll a,b,c;
__int128 _a,_b;
ll mul(ll a,ll b){
_a=a,_b=b;
return _a*_b%p;
}
void slove(ll fz1,ll fm1,ll fz2,ll fm2,ll &b,ll & c){//仿造辗转相除法
ll z1=fz1/fm1,z2=fz2/fm2;
if(z1!=z2){
b=z1+1;
c=1;
return;
}
fz1-=fm1*z1;
fz2-=fm2*z1;
slove(fm2,fz2,fm1,fz1,c,b);
b+=c*z1;
}
int main(){
freopen("D:/compare/1.in","r",stdin);
freopen("D:/compare/oj.txt","w",stdout);
scanf("%d",&t);
while(t--){
scanf("%lld%lld",&p,&x);
slove(p,x,p,x-1,b,c);
//a=b*x-c*p;
/*dls的代码求a是这样写的,但我感觉这样溢出后答案会有问题吧。
可数据测出来没问题,令人头大*/
a=mul(b,x);
printf("%lld/%lld\n",a,b);
}
return 0;
}
- 后记
比赛时推出了1式但不会解,还是太菜了,还要多练啊,革命尚未成功,同志仍需努力。