辗转相除法
2016-02-11 20:45
295 查看
利用辗转相除法求 两数的最大公因数 或 最小公倍数
例如 求6497和3869的最大公因数和最小公倍数
6497÷3869=1……2628
3869÷2628=1……1241
2628÷1241=1……146
1241÷146=8……73
146÷73=2……0
则 最大公因数为 73
最小公倍数为 6497×3869÷73=344341
如下 代码
例如 求6497和3869的最大公因数和最小公倍数
6497÷3869=1……2628
3869÷2628=1……1241
2628÷1241=1……146
1241÷146=8……73
146÷73=2……0
则 最大公因数为 73
最小公倍数为 6497×3869÷73=344341
如下 代码
#include<iostream> using namespace std; int s[500]; __int64 x,y; int g(int a,int b) { int i,t; y=a*b; if(a<b){ t=a; a=b; b=t; } while(b){ t=b; b=a%b; a=t; } return y/a; // a为两数的最大公因数,y/a为两数的最小公倍数 } void f(int s[],int n) { x=s[0]; for(int i=1;i<n;i++){ x=g(s[i],x); } cout<<x<<endl; } int main() { int n; cin>>n; while(n--){ int a; cin>>a; for(int i=0;i<a;i++)cin>>s[i]; //求数组s中所有数的最大公因数最小公倍数 f(s,a); } //system("pause"); return 0; }
相关文章推荐
- 【Leetcode】Nim Game
- HDOJ 2045 不容易系列之(3)—— LELE的RPG难题
- 图的广度优先遍历
- LeetCode131. Palindrome Partitioning
- JAVA常见基本术语
- hdu 3172 Virtual Friends 带权并查集
- 日本 IT 相关网站
- HDU2103Family planning
- web开发中比较常用的html标签
- 51Nod 1289 大鱼吃小鱼(模拟 有趣)
- poj 3080 Blue Jeans【KMP】【求公共子串】
- 1025. PAT Ranking (25)
- poj 3450 Corporate Identity 【KMP】【求公共子串】
- java synchronized详解(转载)
- hdu1009
- 以创业者的姿态做一名工程师
- TopCoder SRM 681 Div. 2 Problem 500 - ExplodingRobots (枚举)
- 递归归并排序
- Linux SAMBA Server setup Guid
- Java多线程ExecutorService.shutdown什么时候执行