GCD of an Array

Problem

The first line has n. The second line has n non-negative integers (not all zero). Print the greatest common divisor of all of them.

Constraints

  • 1 <= n <= 10^5
  • 0 <= a[i] <= 10^9

Examples

Input

3
12 18 24

Output

6

Solutions

Best approachTime O(n log max)Space O(1)

gcd(a, b, c) = gcd(gcd(a, b), c). We fold the array from left to right with Euclid's algorithm.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Find the gcd of many numbers.
 * Input   : n, then n integers.
 * Output  : The gcd.
 * Approach: gcd(a, b, c) = gcd(gcd(a, b), c).
 * Time    : O(n log max)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: The gcd of one number is the number itself. Start with the first one.
        long result = a[0];

        // Step 2: Combine the result with the next number using Euclid's algorithm.
        for (int i = 1; i < a.length; i++) {
            long x = result;
            long y = a[i];
            while (y != 0) {
                long remainder = x % y;
                x = y;
                y = remainder;
            }
            result = x;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. How do you get the gcd of 3 numbers from the gcd of 2?