扩展欧几里德求逆元 hdoj 1576
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1576
题目思路:自学了扩展欧几里德后,遇到题目就有点感觉,mod除数没办法做就求其逆元来求解,在2016年百度之星资格赛的第一题,也有类似的思想。
若没有接触过扩展欧几里德,可以点击:
http://blog.csdn.net/qq_33199236/article/details/51429013
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[N];
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;
}