LeetCode 2427. Number of Common Factors

Given two positive integers a and b, return the number of common factors of a and b.

An integer x is a common factor of a and b if x divides both a and b.

Example 1:

Input: a = 12, b = 6
Output: 4
Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.

Example 2:

Input: a = 25, b = 30
Output: 2
Explanation: The common factors of 25 and 30 are 1, 5.

Constraints:

  • 1 <= a, b <= 1000

这题就是求两个数字的所有共同约数,就是同时能被a和b整除。最最简单的做法就是从1遍历到两个数里更小的那个,每个数字除一下判断一下就行。

class Solution {
    public int commonFactors(int a, int b) {
        int result = 0;
        int min = Math.min(a, b);
        for (int i = 1; i <= min; i++) {
            if (a % i == 0 && b % i == 0) {
                result++;
            }
        }
        return result;
    }
}

也有人用gcd先求出上限,然后再遍历的,我觉得可以但没必要?以及永远也记不住gcd的算法。这次试图理解了一下,大概就是repeatedly replace the larger number with the diff between the larger and the smaller number。

class Solution {
    public int commonFactors(int a, int b) {
        int result = 0;
        int gcd = gcd(a, b);
        for (int i = 1; i <= gcd; i++) {
            if (gcd % i == 0) {
                result++;
            }
        }
        return result;
    }

    private int gcd(int a, int b) {
        if (b == 0) {
            return a;
        } else {
            return gcd(b, a % b);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值