gcd相关 2654

发布时间 2023-04-24 01:44:28作者: xiaoyongyong

如何求取两个数字的最大公约数?

原理:a和b的最大公约数,也是a和a%b的最大公约数

   private int gcd(int a, int b) {
       //如果b为0,那么直接返回a
        if(b == 0) return a;
       //如果a可以被b整除,那么返回b
        if(a % b == 0) return b;
       //否则求取b和a%b的最大公约数
        return gcd(b, a % b);
   }

 

2654. Minimum Number of Operations to Make All Array Elements Equal to 1
Medium

You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times:

  • Select an index i such that 0 <= i < n - 1 and replace either of nums[i] or nums[i+1] with their gcd value.

Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1.

The gcd of two integers is the greatest common divisor of the two integers.

 Example 1:

Input: nums = [2,6,3,4]
Output: 4
Explanation: We can do the following operations:
- Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4].
- Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4].
- Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4].
- Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1].

Example 2:

Input: nums = [2,10,6,14]
Output: -1
Explanation: It can be shown that it is impossible to make all the elements equal to 1.

 Constraints:

  • 2 <= nums.length <= 50
  • 1 <= nums[i] <= 106
class Solution {
   public int minOperations(int[] nums) {
       int ones = 0;
       int totalGcd = nums[0];
       for(int i = 0; i < nums.length; i++) {
           ones += (nums[i] == 1) ? 1 : 0;
           totalGcd = gcd(totalGcd, nums[i]);
       }
       //1.如果所有数字gcd>1,那么不可能化解为1
       if(totalGcd > 1) return -1;
       //2.如果数组中已经有1,那么只需要len-count(1)
       if(ones > 0) return nums.length - ones;
       //3.如果没有1,则找出gcd为1的最小子数组,结果就是:len(subarray) - 1 + len - 1
       int minLen = nums.length;
       for(int i = 0; i < nums.length; i++) {
           int currGcd = nums[i];
           for(int j = i + 1; j < nums.length; j++) {
               currGcd = gcd(currGcd, nums[j]);
               if(currGcd == 1) {
                   minLen = Math.min(minLen, j - i + 1);
                   break;
               }
           }
       }
       return minLen - 1 + nums.length - 1;
   }
   private int gcd(int a, int b) {
       //如果b为0,那么直接返回a
        if(b == 0) return a;
       //如果a可以被b整除,那么返回b
        if(a % b == 0) return b;
       //否则求取b和a%b的最大公约数
        return gcd(b, a % b);
   }
}