Saturday, January 14, 2017

Greatest Common Divisor

Given an array of Integers, return the greatest common divisor of all the numbers in the array.

/*
time:O(n?), space:O(1)
*/

import java.util.*;

public class Solution {
    public static int gcd(int[] A) {
        if (A == null || A.length <= 1) {
            return 0;
        }
        int num = A[0];
        for (int i = 1; i < A.length; i++) {
            num = calGCD(num, A[i]);
            if (num == 1) {
                return 1;
            }
        }
        return num;
    }
    public static int calGCD(int a, int b) {
        while (a % b != 0) {
            int k = a % b;
            a = b;
            b = k;
        }
        return b;
    }

    public static void main(String[] args) {
        int[] A = {2,3,6,7};
        int res = gcd(A);
        System.out.print(res);
        
    }
}

No comments:

Post a Comment