HDU 2019 Multi-University Training Contest 5 杭电多校联合训练赛 第五场 1001 fraction(6624)

HDU 2019 Multi-University Training Contest 5 杭电多校联合训练赛 第五场 1001 fraction(6624)

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

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

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


题意

给定p和x,求a*b-1 =x (mod p)中b的最小值,输出a/b,gcd(a,b)==1。

思路

a* b-1=x (mod p)
=> a=x* b-p* b* t
=>(记b* t为y) a=x* b-p* y
=>(因为0 =>p/x < b/y

运用辗转相除法求形如la/lb < x/y < ra/rb的式子的x,y的最小值的某算法
算法实现如下:HDU 2019 Multi-University Training Contest 5 杭电多校联合训练赛 第五场 1001 fraction(6624)_第1张图片

坑点

想不到,看不懂,学不会,只会用板子


代码

f函数的使用和exgcd的使用是基本类似的,求出y和b之后代回第一条式子求出a即可。

#include 

using namespace std;

typedef long long ll;

void f(ll la,ll lb,ll ra,ll rb,ll& x,ll& y)
{
	ll minint=la/lb+1;
	if(minint<=ra/rb)
	{
		x=minint;
		y=1;
		return ;
	}
	minint--;
	la-=minint*lb; ra-=minint*rb;
	f(rb,ra,lb,la,y,x);
	x+=minint*y;
	return ;

}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        ll a,p;
        scanf("%lld%lld",&p,&a);
        ll x,y;
        f(p,a,p,a-1,x,y);
        y=x*a-y*p;
        printf("%lld/%lld\n",y,x);
    }
    return 0;
}

你可能感兴趣的:(ACM)