zoukankan      html  css  js  c++  java
  • (杭电1019 最小公倍数) Least Common Multiple

    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;
    }

  • 相关阅读:
    [HAOI2008] 硬币购物
    [HNOI2002] Kathy 函数
    [SCOI2009] windy数
    圆方树总结
    ABOUT ME && 友链
    逝念偶拾
    文化课日常
    记一些欢愉
    浅谈
    洛谷 4823 [TJOI2013]拯救小矮人
  • 原文地址:https://www.cnblogs.com/cafu-chino/p/10060320.html
Copyright © 2011-2022 走看看