hdu1576 A/B(求逆元模板)

来源:互联网 发布:linux禅道启动命令 编辑:程序博客网 时间:2024/06/05 12:48

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

题解:让你求A/B其实就是让你求A*1/B即让你求解B的逆元则题目就迎刃而解。

普及下逆元的知识:

逆元:使得ax≡1(mod n)一个数有逆元的充分必要条件是gcd(a,n)=1,此时逆元唯一存在 (个人理解)

解逆元思路:

给定模数m,求a的逆相当于求解ax=1(mod m)
这个方程可以转化为ax-my=1,这一步最关键,x为所求,a为已知数,m为已知数mod
然后套用求二元一次方程的方法,用扩展欧几里得算法求得一组x0,y0和gcd 
检查gcd是否为1 
gcd不为1则说明逆元不存在

求逆元模板代码:

int exgcd(int a,int b,int &x,int &y){    if(b==0){        x=1;        y=0;        return a;    }    int ans=exgcd(b,a%b,x,y);    int temp=x;    x=y;    y=temp-a/b*y;    return ans;}//求逆元的模板,gcd为1说明逆元存在,gcd不为1说明逆元不存在int inverse(int a,int n)//n为mod的那个数{    int d,x,y;    d=exgcd(a,n,x,y);    return d==1?(x+n)%n:-1;}

本题题解:

#include <iostream>#include <cstdio>using namespace std;int exgcd(int a,int b,int &x,int &y){    if(b==0){        x=1;        y=0;        return a;    }    int ans=exgcd(b,a%b,x,y);    int temp=x;    x=y;    y=temp-a/b*y;    return ans;}//求逆元的模板,gcd为1说明逆元不存在int inverse(int a,int n){    int d,x,y;    d=exgcd(a,n,x,y);    return d==1?(x+n)%n:-1;}int main(){    int n;scanf("%d",&n);while(n--){        int a,b;scanf("%d%d",&a,&b);        int ansb=inverse(b,9973);        printf("%d\n",a*ansb%9973);    }}



 

1 0