Algo.Java.GCDandLCM

GCD is greatest common divisor

// naive approach

    private static int getGCD(int num1, int num2) {
        int max = Integer.MIN_VALUE;
        int minNum = Math.min(num1, num2);
        for (int i = 1; i <= minNum; i++) {
            if (num1 % i == 0 && num2 % i == 0) {
                max = Math.max(max, i);
            }
        }
        return max;
    }

// more elegant way

    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

// least common multiple

lcm = (lcm * nums[j]) / gcd((int) lcm, nums[j]);
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.