首页 > ACM题库 > HDU-杭电 > HDU 1019 Least Common Multiple-递推-[解题报告] C++
2013
11-26

HDU 1019 Least Common Multiple-递推-[解题报告] C++

Least Common Multiple

问题描述 :

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 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.

输出:

For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.

样例输入:

2
3 5 7 15
6 4 10296 936 1287 792 1

样例输出:

105
10296

这一题是比较基础的数论题了,求N个数的最小公倍数,思路就是先求出两个数的最小公倍数,然后再用这个最小公倍数与下一个数求最小公倍数,则得三个数的最小公倍数,然后再用这三个数的最小公倍数与第四个数求最小公倍数,得这四个数的最小公倍数……如此递推,就OK了。不过要注意算最小公倍数的时候小心数据溢出!

AC code:

1 #include <iostream>
 2 using namespace std;
 3 int n, m;
 4 int arr[1000];
 5 
 6 int gcd(int a, int b) //求出最大公约数
 7 {
 8     if(b)
 9         return gcd(b, a % b);
10     else 
11         return a;
12 }
13 int lcm(int a, int b)  //注意这里不能用a*b/gcd(a,b),数据会溢出
14 {
15     return a  / gcd(a, b) * b;
16 }
17 int main()
18 {
19     while(scanf("%d", &n) != EOF)
20     {
21         while(n--){
22             scanf("%d", &m);
23             int first;
24             scanf("%d", &first);
25             for (int i = 1; i < m; i++)   //两两计算最小公倍数
26             {
27                 scanf("%d", &arr[i]);
28                 first = lcm(first, arr[i]);
29             }
30             printf("%d\n", first);
31         }
32     }
33 }

 


  1. 第23行:
    hash = -1是否应该改成hash[s ] = -1

    因为是要把从字符串s的start位到当前位在hash中重置

    修改提交后能accept,但是不修改居然也能accept

  2. 5.1处,反了;“上一个操作符的优先级比操作符ch的优先级大,或栈是空的就入栈。”如代码所述,应为“上一个操作符的优先级比操作符ch的优先级小,或栈是空的就入栈。”