Modular Inverse(模线性方程)
2014-03-09 10:46
232 查看
http://acm.sdut.edu.cn:8080/vjudge/contest/view.action?cid=89#problem/F
求解
原式相当于 ax(mod m) = 1(mod m),那么 ax-1 是m的倍数。 设ax-1 = my ——> ax - my = 1。
该式有解的前提是 1 是 a和m的最大公约数的倍数,因此 a 和 m 互质,方程有唯一解。
然后再用扩展欧几里得。注意m等于1的时候x的最小值是1。
求解
ax≡1 (mod m).
原式相当于 ax(mod m) = 1(mod m),那么 ax-1 是m的倍数。 设ax-1 = my ——> ax - my = 1。
该式有解的前提是 1 是 a和m的最大公约数的倍数,因此 a 和 m 互质,方程有唯一解。
然后再用扩展欧几里得。注意m等于1的时候x的最小值是1。
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int gcd(int a, int b) { if(b == 0) return a; return gcd(b,a%b); } int extend_gcd(int a, int b, int &x, int &y) { if(b == 0) { x = 1; y = 0; return a; } int r = extend_gcd(b,a%b,y,x); y -= x*(a/b); return r; } int main() { int test; int a,m; scanf("%d",&test); while(test--) { scanf("%d %d",&a,&m); if(m == 1) { printf("1\n"); continue; } if(gcd(a,m) != 1) { printf("Not Exist\n"); continue; } int x,y; extend_gcd(a,m,x,y); if(x < 0) x += m; printf("%d\n",x); } return 0; }
相关文章推荐
- Modular Inverse [a关于模m的逆 模线性方程]
- GCD 扩展GCD 快速GCD 模线性方程 模线性方程组 单独求欧拉函数 递推求欧拉函数
- C语言解线性方程的四种方法
- [poj 2115]C Looooops[扩展欧几里德][模线性方程]
- C Looooops(扩展欧几里得求模线性方程)
- poj2115——C Looooops(数论,解模线性方程)
- 用matlab求线性方程的解
- gcd欧几里得,线性模方程
- MTL 矩阵逆阵 解线性方程
- 模线性方程(组)
- pku 1061 青蛙的约会(解模线性方程)
- 高斯消元同余线性方程的模板
- 多元线性回归方程建模:使用岭回归与lasso算法选择变量
- 线性模方程求解
- 求模线性方程的一个有力定理
- 【数值分析】误差的分析与减少及Matlab解线性方程的四种方法
- 算法导论-----数论-----求解模线性方程
- AndrewNg - 线性回归【2】正规方程组
- 线性方程求法分类
- ZOJ 3609 Modular Inverse【exgcd】