杭电1019Least Common Multiple
Posted weeping
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了杭电1019Least Common Multiple相关的知识,希望对你有一定的参考价值。
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1019
题目:
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
2
3 5 7 15
6 4 10296 936 1287 792 1
Sample Output
105
10296
思路:最小公倍数(lcm),最大公约数(gcd)。
求gcd(a,b),用辗转相除法。
代码:
View Code
long gcd(long a,long b) { long r=1; while (r>0) { r=a%b; a=b; b=r; } return a;}
lcm(a,b)=a*b/gcd(a,b);
代码:
long lcm(long a,long b) { return a/gcd(a,b)*b; }
ac代码:
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cmath> 5 #include <cstring> 6 #include <queue> 7 #include <stack> 8 #include <map> 9 #include <vector> 10 11 #define PI acos((double)-1) 12 #define E exp(double(1)) 13 using namespace std; 14 15 long gcd(long a,long b) 16 { 17 18 long r=1; 19 while (r>0) 20 { 21 r=a%b; 22 a=b; 23 b=r; 24 } 25 return a; 26 // if(b) 27 // while( (a%=b) && (b %= a)); 28 // return a+b; 29 } 30 31 long lcm(long a,long b) 32 { 33 return a/gcd(a,b)*b; 34 } 35 int main (void) 36 { 37 int t,n; 38 cin>>t; 39 while(t--) 40 { 41 long temp,m; 42 cin>>n; 43 scanf("%ld",&temp); 44 for(int i = 1;i<n;i++) 45 { 46 scanf("%ld",&m); 47 temp = lcm(temp,m); 48 } 49 cout<<temp<<endl; 50 51 } 52 return 0; 53 }
以上是关于杭电1019Least Common Multiple的主要内容,如果未能解决你的问题,请参考以下文章
HDU 1019 Least Common Multiple 数学题
hdu 1019 Least Common Multiple
HDU 1019 Least Common Multiple
HDUJ 1019 Least Common Multiple