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<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


題意

給定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<a<b)0<x* b-p* y<b
=>p/x < b/y <p/(x-1)
運用輾轉相除法求形如la/lb < x/y < ra/rb的式子的x,y的最小值的某算法
算法實現如下:在這裏插入圖片描述

坑點

想不到,看不懂,學不會,只會用板子


代碼

f函數的使用和exgcd的使用是基本類似的,求出y和b之後代回第一條式子求出a即可。

#include <bits/stdc++.h>

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;
}

發佈了44 篇原創文章 · 獲贊 6 · 訪問量 4548
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章