求一组数的最简整数比

public class Solution {
    
    /**
     * 两个数的最大公约数
     */
    public static int greatestCommonDivisor(int m, int n) {
        if (n == 0) {
            return m;
        }
        int r = m % n;
        return greatestCommonDivisor(n, r);
    }
    
    /**
     * 一组数的最大公约数
     */
    public static int greatestCommonDivisor(List numbers) {
        return numbers.stream().reduce(Solution::greatestCommonDivisor).get();
    }
    
    /**
     * 一组数的最简整数比
     */
    public static List simplestIntegerRatio(List numbers) {
        int gcd = greatestCommonDivisor(numbers);
        return numbers.stream().map(p -> p / gcd).collect(Collectors.toList());
    }
    
    
    public static void main(String[] args){
        List numbers = new ArrayList<>();
        numbers.add(20);
        numbers.add(8);
        numbers.add(60);
        System.out.println(simplestIntegerRatio(numbers));
    }
    
}

你可能感兴趣的:(算法,算法)