Modular Inverse ZOJ - 3609(扩展欧几里得求逆元)

Modular Inverse

题目链接: ZOJ - 3609

给定模数m, 求a的逆元x, 相当于求解ax≡1(modm);可以转化成方程ax+my=1;此时可以用扩展欧几里得求得r=gcd(a, m);
若r!=1则不存在x是a的逆元;
若r==1, 扩展欧几里得所求出的x即为a的逆元x, 此时再将x调整到0~m-1范围;就求得a的逆元;
那么怎么调整x呢;
其实x,y是ax+my=1的一个特解, 其通解是x+m*t,  y+a*t;这时通过改变t来调整x就好了;
#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h> 
using namespace std;
int exgcd(int a, int b, int &x, int &y){
	if(b==0){
		x=1; y=0;
		return a;
	}
	int r=exgcd(b, a%b, x, y);
	int t=x;
	x=y;
	y=t-a/b*y;
	return r;
}
int main(){
	int T;
	cin >> T;
	while(T--){
		int a, m, x, y;
		cin >>a >> m;
		int r = exgcd(a, m, x, y);
		if(r!=1) cout << "Not Exist\n";
		else{
			while(x<=0){
				x+=m;
			}
			cout << x << endl;
		} 
	}
	return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值