您的位置:首页 > 其它

扩展欧几里德求逆元 hdoj 1576

2016-05-20 20:50 267 查看

扩展欧几里德求逆元 hdoj 1576

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1576

题目思路:自学了扩展欧几里德后,遇到题目就有点感觉,mod除数没办法做就求其逆元来求解,在2016年百度之星资格赛的第一题,也有类似的思想。

若没有接触过扩展欧几里德,可以点击:

/article/8247663.html

ac代码:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
#define N 10000
#define PI 3.1415927
#define mod 9973
int exgcd(int a,int b,int& x,int& y)
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
int d = exgcd(b, a%b ,x ,y);
int temp = x;
x = y;
y = temp - a/b*y;
return d;
}
int inv
;
int main()
{
//----------------------------------------
inv[0]=0,inv[1]=1;
for(int i=2;i<=mod+10;i++)
{
inv[i]=inv[mod%i]*(mod-mod/i)%mod;
}
//----------------------------------------
int t;
scanf("%d",&t);
while(t--)
{
int a,b;
scanf("%d%d",&a,&b);
int x,y;
exgcd(b,mod,x,y);
while(x < 0)
x += mod;
int ans;
ans = a * x % mod;
printf("%d\n",ans);
}
return 0;
}


上面有部分是可以快速求乘法逆元的模版。

inv[i] 就为 i 的逆元

inv[0]=0,inv[1]=1;
for(int i=2;i<=mod+10;i++)
{
inv[i]=inv[mod%i]*(mod-mod/i)%mod;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: