算法系列——找出数组的最大公约数

Posted BridgeGeorge

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法系列——找出数组的最大公约数相关的知识,希望对你有一定的参考价值。

题目

给你一个整数数组 nums ,返回数组中最大数和最小数的 最大公约数 。

两个数的 最大公约数 是能够被两个数整除的最大正整数。

题目链接:https://leetcode-cn.com/problems/find-greatest-common-divisor-of-array/

解答

辗转相除法。

class Solution 
    public int findGCD(int[] nums) 
        if(nums==null || nums.length==0)
            return Integer.MIN_VALUE;
        
        int min=nums[0];
        int max=nums[0];
        for(int i=1;i<nums.length;i++)
            min=Math.min(min,nums[i]);
            max=Math.max(max,nums[i]);
        
        return gcd(min,max);
    

     public int gcd (int a, int b) 
        // write code here
        return a == 0 ? b : gcd(b%a, a);
    

以上是关于算法系列——找出数组的最大公约数的主要内容,如果未能解决你的问题,请参考以下文章