HDU 1019 Least Common Multiple
来源:互联网 发布:淘宝华佗大药房保真吗 编辑:程序博客网 时间:2024/05/23 14:30
Problem Description
The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105.
Input
Input will consist of multiple problem instances. The first line of the input will contain a single integer indicating the number of problem instances. Each instance will consist of a single line of the form m n1 n2 n3 ... nm where m is the number of integers in the set and n1 ... nm are the integers. All integers will be positive and lie within the range of a 32-bit integer.
Output
For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.
Sample Input
23 5 7 156 4 10296 936 1287 792 1
Sample Output
10510296题意:求多个数的最小公倍数。思路:辗转相除法:1来源编辑
设两数为a、b(a>b),求a和b最大公约数(a,b)的步骤如下:用b除a,得a÷b=q......r1(0≤r1)。若r1=0,则(a,b)=b;若r1≠0,则再用r1除b,得b÷r1=q......r2 (0≤r2).若r2=0,则(a,b)=r1,若r2≠0,则继续用r2除r1,……如此下去,直到能整除为止。其最后一个非零除数即为(a,b)。2原理编辑
设两数为a、b(b<a),用gcd(a,b)表示a,b的最大公约数,r=a mod b 为a除以b以后的余数,k为a除以b的商,即a÷b=k.......r。辗转相除法即是要证明gcd(a,b)=gcd(b,r)。第一步:令c=gcd(a,b),则设a=mc,b=nc第二步:根据前提可知r =a-kb=mc-knc=(m-kn)c第三步:根据第二步结果可知c也是r的因数第四步:可以断定m-kn与n互质【否则,可设m-kn=xd,n=yd,(d>1),则m=kn+xd=kyd+xd=(ky+x)d,则a=mc=(ky+x)dc,b=nc=ycd,故a与b最大公约数成为cd,而非c,与前面结论矛盾】从而可知gcd(b,r)=c,继而gcd(a,b)=gcd(b,r)。证毕。思路:辗转相除法写成函数;多次调用就行了。
#include<stdio.h>int gcd(int a,int b){ if(a<b) // 记得判断大小。 { int temp; temp=a; a=b; b=temp; } if(a%b==0) //结束条件 { return b; } else { return gcd(b,a%b); }}int main(){ int n; scanf("%d",&n); int i; while(n--) { int m; scanf("%d",&m); int res; int x; scanf("%d",&res); for(i=2;i<=m;i++) { scanf("%d",&x); res=res/gcd(res,x)*x; } printf("%d\n",res); } return 0;}
0 0
- HDU 1019 Least Common Multiple
- hdu 1019 Least Common Multiple
- HDU-1019 least common multiple
- HDU 1019 Least Common Multiple
- HDU 1019 Least Common Multiple
- HDU 1019 Least Common Multiple
- HDU 1019 Least Common Multiple
- hdu 1019Least Common Multiple
- hdu 1019 Least Common Multiple
- hdu 1019 Least Common Multiple
- Hdu 1019 Least Common Multiple
- hdu 1019 Least Common Multiple
- HDU 1019Least Common Multiple
- hdu 1019 Least Common Multiple
- hdu 1019 Least Common Multiple
- hdu 1019 Least Common Multiple
- HDU 1019 Least Common Multiple
- hdu 1019 Least Common Multiple
- 登录界面 Android简单http get请求(含服务器端)三
- poj 1095 递归(Catalan)
- 项目中使用Quartz集群分享--转载
- 大型测试开发交流大会
- ROW_NUMBER() OVER函数的基本用法用法
- HDU 1019 Least Common Multiple
- C++11多线程学习记录(一)
- Prim算法和Kruskal算法
- MINA学习第一节
- hosts文件
- 优秀的开源网站(不断更新)
- Quaternion 学习与应用
- iOS单例模式
- android 聊天记录时间的设置