Least Common Multiple HDU 1019
来源:互联网 发布:jsp mysql 用户注册 编辑:程序博客网 时间:2024/06/05 15:52
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; }
阅读全文
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 蓝牙获取心率
- book1 unit1 after-class reading 2 : We All Need Friends
- android menu
- 2017.8
- Least Common Multiple HDU 1019
- Binder实用指南(二)
- 《算法入门经典》的答案
- 数组
- Spring Boot属性配置文件详解
- 51nod 1677 treecnt 组合数
- xmzl大佬
- Android 性能优化之 String篇
- cansult大佬