You are given a list of positive whole numbers. Print the greatest number that divides all of them.
What to build
Start with the first number as the answer. For each next number, replace the answer by gcd(answer, number).
Requirements
- Use Euclid's algorithm (
gcdor your own function) - Use
long long
Input
The first line has n. The second line has n positive numbers.
Output
The gcd of all the numbers.
Constraints
1 ≤ n ≤ 100,000. Numbers are from 1 to 10¹⁸.
Example
Input:
3
12 18 30
Output:
6
Why it works
The gcd of a list can be built one number at a time because gcd(a, b, c) = gcd(gcd(a, b), c). Each step costs O(log) and the result can only get smaller or stay the same.
Examples
3 12 18 30
6
2 7 13
1
Hints
Hint 1
long long g = a[0]; then g = gcd(g, a[i]) for every other number.
Hint 2
You can write your own: long long gcd2(long long a, long long b) { return b == 0 ? a : gcd2(b, a % b); }
Hint 3
gcd(x, 1) is 1, so the answer is never below 1.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
long long gcd2(long long a, long long b) {
while (b != 0) {
long long t = a % b;
a = b;
b = t;
}
return a;
}
int main() {
int n;
cin >> n;
long long g = 0;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
g = gcd2(g, x);
}
cout << g << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step