📜  最大数除以数组中的最大元素数

📅  最后修改于: 2021-04-29 01:15:06             🧑  作者: Mango

给定长度为N的数组arr [] ,任务是找到将数组中元素的最大数量除以最大的数字。

例子:

方法:解决此问题的直接方法是采用所有要素的GCD。为什么这种方法行得通? 1是将数组的所有元素相除的数字。现在,任何其他大于1的数字都将除以数组的所有元素(在这种情况下,数字本身就是答案)或它将除以数组的一个子集,即1为答案,因为它从中除以更多元素数组。因此,最直接的方法是获取数组所有元素的GCD。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the largest number
// that divides the maximum elements
// from the given array
int findLargest(int* arr, int n)
{
 
    // Finding gcd of all the numbers
    // in the array
    int gcd = 0;
    for (int i = 0; i < n; i++)
        gcd = __gcd(arr[i], gcd);
    return gcd;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 6, 9 };
    int n = sizeof(arr) / sizeof(int);
 
    cout << findLargest(arr, n);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG {
 
    // Function to return the largest number
    // that divides the maximum elements
    // fom the given array
    static int findLargest(int[] arr, int n)
    {
 
        // Finding gcd of all the numbers
        // in the array
        int gcd = 0;
        for (int i = 0; i < n; i++)
            gcd = __gcd(arr[i], gcd);
        return gcd;
    }
 
    static int __gcd(int a, int b)
    {
        return b == 0 ? a : __gcd(b, a % b);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 3, 6, 9 };
        int n = arr.length;
 
        System.out.print(findLargest(arr, n));
    }
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 implementation of the approach
from math import gcd as __gcd
 
# Function to return the largest number
# that divides the maximum elements
# fom the given array
def findLargest(arr, n):
 
    # Finding gcd of all the numbers
    # in the array
    gcd = 0
    for i in range(n):
        gcd = __gcd(arr[i], gcd)
    return gcd
 
# Driver code
if __name__ == '__main__':
    arr = [3, 6, 9]
    n = len(arr)
 
    print(findLargest(arr, n))
 
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
 
class GFG {
 
    // Function to return the largest number
    // that divides the maximum elements
    // fom the given array
    static int findLargest(int[] arr, int n)
    {
 
        // Finding gcd of all the numbers
        // in the array
        int gcd = 0;
        for (int i = 0; i < n; i++)
            gcd = __gcd(arr[i], gcd);
        return gcd;
    }
 
    static int __gcd(int a, int b)
    {
        return b == 0 ? a : __gcd(b, a % b);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 3, 6, 9 };
        int n = arr.Length;
 
        Console.Write(findLargest(arr, n));
    }
}
 
// This code is contributed by PrinciRaj1992


输出
3

时间复杂度: O(N * log(N))
辅助空间: O(N)