Least Common Multiple HDU 1019
2017-08-27 15:23
381 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1019
HDU 1019 题目链接;
分析:这是一道基础的考察最大公约数和最小公倍数的题目。
在高中时学过辗转相除法来求得两个数的最大公约数,比起一般的运算这种方法在空间复杂度和时间复杂度上都占优势。
原理分析:辗转相除就是用两个数中较大的一个数(被除数)对较小(除数)的一个数进行取余,取得的余数与除数接着取余(依然是较大的对较小的)直到取得的余数为零时另一个数便是所求的最大公约数。
代码实现
迭代版本
int f( int a, int b) { if( a < b ) { int t; t = a; a = b; b = t; } int ans; while( b ) // 直到一方取余为零 { ans = a % b; a =b; b = ans; } return ans; }
递归版本
int f( int a, int b) { if( a < b) { int t; t = a; a = b; b = t; } return b==0 ? a : f( b, a%b); }
本题AC代码
#include<stdio.h> #include<algorithm> using namespace std; int mark[10010]; /*int f(int a, int b) { if( a < b) swap( a, b); return b == 0?a : f( b, a%b); } */ int f(int a,int b) { int ans; if(a < b) swap( a, b); while( b ) { ans=a%b; a=b; b=ans; } return a; } int main() { int t,a,b,m; scanf("%d",&t); for( int i = 0; i < t; i ++) { int ans; scanf("%d",&m); scanf("%d",&a); ans=a; for(int j = 1; j < m; j ++) { scanf( "%d", &b); ans = b/f( ans, b)*ans; } printf("%d\n",ans); } return 0; }
相关文章推荐
- hdu 1019 Least Common Multiple(最小公倍数)
- HDU 1019 Least Common Multiple
- hdu 1019 Least Common Multiple
- hdu 1019 Least Common Multiple (水题,LCM)
- 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 (最小公倍数)
- hdu1019 Least Common Multiple
- HDU 1019 Least Common Multiple
- hdu_1019 Least Common Multiple(最小公倍数)
- HDU 1019 Least Common Multiple(最小公倍数&最大公约数熟悉)
- HDU-1019-Least Common Multiple( 最大公约数 && 最小公倍数 && GCD )
- hdu 1019 Least Common Multiple
- hdu1019--Least Common Multiple
- HDU 1019 Least Common Multiple(求多个数字的最小公倍数)
- hdu_1019Least Common Multiple(最小公倍数)
- Least Common Multiple (HDU 1019)
- HDU 1019 Least Common Multiple【GCD】