HDU - 1576 欧几里得扩展 求mod的逆

要求(A/B)%9973,但由于A很大,我们只给出n(n=A%9973)(我们给定的A必能被B整除,且gcd(B,9973) = 1)。
Input
数据的第一行是一个T,表示有T组数据。
每组数据有两个数n(0 <= n < 9973)和B(1 <= B <= 10^9)。
Output
对应每组数据输出(A/B)%9973。
Sample Input
2
1000 53
87 123456789
Sample Output
7922
6060

我的见解:有gcd欧几里得的常见符号 拓展一下
欧几里得公式:

int gcd1(int a, int b)             //欧几里得原始公式1
{
	return b == 0 ? a : gcd1(b, a%b); 
}

int gcd2(int a, int b)             //欧几里得原始公式2
{
	if (b == 0)return a;
	else gcd2(a, a%b);
}

欧几里得的拓展:

当 gcd ( a , b )= d 时,求绝对值和最小的 x , y 使得 x * a + y * b = d ;

d = gcd ( a , b ) = gcd ( b , a mod b );

设:

x1 * a + y1 * b = d ;        ①

x2 * b + y2 * ( a mod b ) = d ;   ②

因为 a mod b = a - ( a / b )* b;  ③(除法为整除)

将③代入②整理得:

y2 * a + ( x2 - ( a / b ) * y2 ) * b = d; ④

由①和④整理得:

x1 = y2 ;
y1 = x2 - ( a / b ) * y2;

将此结论代入递归函数既得。

int extgcd(int a, int b, int &x, int &y)   //扩展欧几里得,求x和y值,课本有个同时求x,y和公约数的,得到的x和y其中有一个是负数
{
	int d = a;
	if (b != 0)
	{
		d = extgcd(b, a%b, y, x);
		y -= (a / b)*x;
	}
	else { x = 1; y = 0; }
	return d;
}

要我们求解(A/B)%9973,当然不能直接求解,你要求一下B的逆元,因为gcd(B,9973) = 1),这就说明 B 相对于模9973是存在逆元 b 的,然后(A/B)%9973就转化为(A * b)%9973 就等于 (n * b)%9973。
注意求到的逆元可能是负数,得处理一下

#pragma warning(disable:4996)
#define K(a)       scanf("%d", &a)
#define KK(a,b)    scanf("%d %d", &a, &b)
#define KKK(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define kd          printf
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<stack>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;

int extgcd(int a,int b, int &x, int &y)   //扩展欧几里得,求x和y值,课本有个同时求x,y和公约数的,得到的x和y其中有一个是负数
{
	int d = a;
	if (b != 0)
	{
		d = extgcd(b, a%b, y, x);
		y -= (a / b)*x;
	}
	else { x = 1; y = 0; }
	return d;
}
int main()
{
	int m, n, x, y, t,b;
	cin >> t;
	while (t--)
	{
		cin >> n >> b;
		extgcd(b, 9973, x, y);
		cout << (n*((x%9973+9973)%9973)) % 9973 << endl;  对可能出现的负数处理一下
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wujiekd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值