扩展欧几里德求不定方程 hdoj 2669
2016-05-21 10:16
330 查看
扩展欧几里德求不定方程 hdoj 2669
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2669题目思路:赤裸裸的求不定方程 p = m * x - n * y;
涉及到扩展欧几里德求不定方程的性质:
对于不定整数方程pa+qb=c,若 c mod Gcd(a, b)=0,则该方程存在整数解,否则不存在p , q整数解。 可以想到,因为c == 1,只有gcd(n,m) == 1,才有解。
根据扩展欧几里德算法,所得到的p,q为其中一个解(且最小),而其他整数解满足:
p = p0 + b/Gcd(p, q) * t
q = q0 - a/Gcd(p, q) * t(其中t为任意整数)
然而这题还有一个细节,x要非负数,所以你懂的,往上加b/Gcd(p, q),直到满足。
若没有接触过扩展欧几里德,可以点击:
/article/8247663.html
ac代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <cstdlib> #include <cmath> #include <map> #include <string> using namespace std; 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 main() { int n,m; while(~scanf("%d%d",&n,&m)) { int x,y; int ans = exgcd(n,m,x,y); if(ans == 1) { while(x<0) { x += m; y -= n; } printf("%d %d\n",x,y); } else printf("sorry\n"); } return 0; }
相关文章推荐
- TCP/IP协议原理与应用笔记23:路由选择模块 和 路由表的设计
- 使用Node.js+Socket.IO搭建WebSocket实时应用
- 面试遇到的问题1
- Dell vostro 5560 定制ubuntu 首次安装配置
- TCP协议中的三次握手和四次挥手(图解)
- 武校学生
- opencv之图像mat复制copyTo,clone=
- 傅里叶分析之掐死教程(完整版)
- Mybatis中resultMap
- IntelliJ IDEA Mac下快捷键
- Eclipse常用快捷键
- 复旦大学老师
- HDU 1086 You can Solve a Geometry Problem too (判断线段交叉,线段跨立)
- ant语法和规范
- 谈谈iOS Animation
- 第十一周上机实践项目 项目4-教师兼职干部类
- Hadoop Configuration 源码详解
- Django笔记 pillow安装错误
- hdoj-2046-骨牌铺方格
- OpenWrt启动过程分析+添加自启动脚本