LeetCode每日一题(2023/4/5)


2427. 公因子的数目

给你两个正整数 a 和 b ,返回 a 和 b 的 公 因子的数目。

如果 x 可以同时整除 a 和 b ,则认为 x 是 a 和 b 的一个 公因子 。

示例 1:

输入:a = 12, b = 6
输出:4
解释:12 和 6 的公因子是 1、2、3、6 。
示例 2:

输入:a = 25, b = 30
输出:2
解释:25 和 30 的公因子是 1、5 。
 
提示:
1 <= a, b <= 1000

解答:用两个List暴力循环求解

class Solution {
        public int commonFactors(int a, int b) {
            List<Integer> res1=help(a);
            List<Integer> res2=help(b);
            int res=0;
            for(int c:res1){
                for (int d:res2){
                    if(c==d)res++;
                }
            }
            return  res;
        }
    List<Integer> help(int a){
        List<Integer> res=new ArrayList<>();
        for (int i = 1; i<=a ; i++) {
            if(a%i==0)res.add(i);
        }
        return res;
    }
}

  目录