zoukankan      html  css  js  c++  java
  • 杭电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),用辗转相除法。
      代码:
    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 }
    View Code
     

    作者:weeping
    出处:www.cnblogs.com/weeping/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    php安装扩展的几种方法
    navicat连接linux系统中mysql-错误:10038
    linux下报错bash: service: command not found
    linux配置防火墙和重启防火墙
    linux 环境安装
    匿名函数
    workman的学习总结
    xampp/apache启动失败解决方法
    Linux 查看IP
    慢查询日志
  • 原文地址:https://www.cnblogs.com/weeping/p/5351874.html
Copyright © 2011-2022 走看看