洛谷P1082 同余方程 数论

洛谷P1082 同余方程
数论
要求 ax === 1 (mod b) 相当于求 ax + by == 1 的解
并要求 x 为最小的正整数
这样我们只要 扩展欧几里德来一发,然后最小正整数 取 mod 就行了

 

但是一般题目里会让你求一个最小的x,当你用拓欧求出一个解时,一般会让你去找一个最小解,
我们只需要对这个数取模b就行了(如果求正数,你只需要先加一个b,再取模行了,应该都知道吧)

 

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cmath>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <iomanip>
 7 #include <iostream>
 8 using namespace std ; 
 9 
10 int n,m,x,y,a,b,t,ans ; 
11 
12 inline int gcd(int a,int b ) 
13 {
14     if(!b) 
15     {
16         x = 1,y = 0 ;
17         return a ; 
18     }
19     
20     int tmp = gcd(b,a%b) ; 
21     t = x ;
22     x = y ; 
23     y = t - a/b*y ; 
24     return tmp ; 
25 }
26 
27 int main() 
28 {
29     scanf("%d%d",&a,&b) ; 
30     ans = gcd(a,b) ;  
31     if(x<0) x+=b ;
32     printf("%d\n",x) ; 
33     
34     return 0 ; 
35 }

 

posted @ 2017-06-01 08:40  third2333  阅读(143)  评论(0编辑  收藏  举报