编程语言
首页 > 编程语言> > hdu 1573扩展欧几里得算法求一元线性同余方程

hdu 1573扩展欧几里得算法求一元线性同余方程

作者:互联网

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

思路:设定mod=9973,由于gcd(B,mod)=1,所以B对mod的逆元B'是可求得,然后(A/B)%mod=(A*B')%mod=((A%mod)*B')%mod=(n*B')%mod;所以本题的关键就是要求B对mod的逆元。

代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned int ui;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 #define pf printf
 7 #define mem(a,b) memset(a,b,sizeof(a))
 8 #define prime1 1e9+7
 9 #define prime2 1e9+9
10 #define pi 3.14159265
11 #define lson l,mid,rt<<1
12 #define rson mid+1,r,rt<<1|1
13 #define scand(x) scanf("%llf",&x) 
14 #define f(i,a,b) for(int i=a;i<=b;i++)
15 #define scan(a) scanf("%d",&a)
16 #define mp(a,b) make_pair((a),(b))
17 #define P pair<int,int>
18 #define dbg(args) cout<<#args<<":"<<args<<endl;
19 #define inf 0x7ffffff
20 inline int read(){
21     int ans=0,w=1;
22     char ch=getchar();
23     while(!isdigit(ch)){if(ch=='-')w=-1;ch=getchar();}
24     while(isdigit(ch))ans=(ans<<3)+(ans<<1)+ch-'0',ch=getchar();
25     return ans*w;
26 }
27 int n,m,t;
28 const int maxn=1e5+10;
29 const int mod=9973;
30 ll exgcd(ll a,ll b,ll &x,ll &y)
31 {
32     if(b==0)
33     {
34         x=1,y=0;
35         return a;
36     }
37     ll ans=exgcd(b,a%b,x,y);
38     ll tmp = x;
39     x=y;
40     y=tmp-(a/b)*y;
41     return ans;
42 }
43 int main()
44 {
45     //freopen("input.txt","r",stdin);
46     //freopen("output.txt","w",stdout);
47     std::ios::sync_with_stdio(false);
48     t=read();
49     while(t--)
50     {
51         ll n,B;
52         scanf("%lld%lld",&n,&B);
53         ll x,y;
54         exgcd(B,mod,x,y);
55         x=(x%mod+mod)%mod;//B的逆元 
56         pf("%lld\n",(x*n)%mod);    
57     }
58 } 

 

标签:hdu,typedef,long,unsigned,同余,1e9,1573,mod,define
来源: https://www.cnblogs.com/randy-lo/p/12742492.html