(杭電1019 最小公倍數) Least Common Multiple

cafu-chino發表於2018-12-03

Least Common Multiple

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 64855 Accepted Submission(s): 24737

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

這道水題連續提交五次,第六次才AC。。。。。。(我真是菜,最近做做的題有點自閉)

這是是我多次修改仍然不AC的題解(測試樣例全過自己測了幾個也沒問題,很絕望)

#include <stdio.h>
#include <math.h>

int main() {
    int t,temp;
    scanf("%d",&t);
    for(int i=1; i <= t; i++) {
        int n;
        scanf("%d",&n);
        for(int j=1; j <= n ; j++) {
            int num;
            scanf("%d",&num);
            if(j == 1) {
                temp=num;
                continue;
            }
            int max;
            if(temp > num)
                max=num;
            else
                max=temp;
            for( ; max >= 1; max--)
                if(temp%max == 0&&num%max == 0)
                    break;
            temp=temp*num/max;
        }
        printf("%d
",temp);
    }
    return 0;
}

最後有dalao指點,把求公因數的方法改成輾轉相乘法並用函式巢狀終於AC 無奈絕望╮(╯﹏╰)╭
關於輾轉相除法求最大公因數,舉個例子:
a=6, b=4; 第一步 a=a%b=6%4=2;
​ 第二步 b=4;
​ 第三步 a%b=2%4=0,此時a == 0,b=(上一步)a;
​ 此時b就是最大公因數;
(算了上詳細講解連結 https://www.cnblogs.com/shine-yr/p/5216966.html

以下為正確程式碼

#include <stdio.h>
#include <math.h>

int gcd(int a,int b){   //輾轉相除法
    
    if(b == 0)
    return a;
    return gcd(b,a%b);
}

int lcm(int a,int b)
{
    return a/gcd(a,b)*b;    //把函式打包
}

int main() {
    int t,temp,n;
    scanf("%d",&t);
    for(int i=1; i <= t; i++) {
        scanf("%d",&n);
        int temp = 1;
        for(int j=1; j <= n ; j++) {
            int num;
            scanf("%d",&num);
            temp = lcm(temp,num);
        }
        printf("%d
",temp);
    }
    return 0;
}

相關文章