zoukankan      html  css  js  c++  java
  • #2028:Lowest Common Multiple Plus(n个数的最小公倍数)

    Problem Description

    求n个数的最小公倍数。

    Input

    输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数。

    Output

    为每组测试数据输出它们的最小公倍数,每个测试实例的输出占一行。你可以假设最后的输出是一个32位的整数。

    Sample Input

    2 4 6
    3 2 5 7
    

    Sample Output

    12
    70
    

    题目分析

    求解n个数的最小公倍数一般有两种做法:

    1. 分解质因数:比较繁琐这里不作解释

    2. 公式法两两运用:

      假设现在要求最小公倍数的两个数为x,y,他们的最大公约数为p,最小公倍数为q。则xy=pq,也就是说只要求得两个数的最大公约数就可求得这两个数的最小公倍数。

      但是题目中要求的是n个数的 最小公倍数,这里只需要用最小公倍数代替原来的两个数即可。

      例如:12 15 8 9

      第一步:求得12和15的最小公倍数为60

      第二部:求得60和8的最小公倍数为120

      第三步:求得120和9的最小公倍数为360

      所以,原问题转换为求两个数的最大公约数。

    辗转相除法求最小公约数

    时间复杂度:(O(lgN))

    int gcd(int a, int c)
    {
    	/*if (c == 0)
    		return a;
    	else
    		return gcd(c, a%c);*/
    
    	return c == 0 ? a :gcd(c, (a%c));
    }
    
    #include<iostream>
    using namespace std;
    int gcd(int a, int c) {
        return c == 0 ? a : gcd(c, (a%c));
    }
    int main() {
        int n;
        int arr[105];//存储数据
        //考虑到溢出的情况,可以使用long long型
        while (cin >> n) {
            for (int i = 1; i <= n; i++) {
                cin >> arr[i];
                if (i != 1) {
                    arr[i] = arr[i - 1] / gcd(arr[i - 1], arr[i])*arr[i];
                }
            }
            cout << arr[n] << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    0309. Best Time to Buy and Sell Stock with Cooldown (M)
    0621. Task Scheduler (M)
    0106. Construct Binary Tree from Inorder and Postorder Traversal (M)
    0258. Add Digits (E)
    0154. Find Minimum in Rotated Sorted Array II (H)
    0797. All Paths From Source to Target (M)
    0260. Single Number III (M)
    0072. Edit Distance (H)
    0103. Binary Tree Zigzag Level Order Traversal (M)
    0312. Burst Balloons (H)
  • 原文地址:https://www.cnblogs.com/RioTian/p/12751128.html
Copyright © 2011-2022 走看看