5

Note:

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two or more numbers is the largest number that divides all of them exactly (with no remainder).

It is found using the Euclidean Algorithm, which is very important for interviews.

Solution 1: Euclidean Algorithm (loop) C++ 7 lines
int a = 12, b = 18;
while(b != 0){
    int temp = b;
    b = a % b;
    a = temp;
}
cout << a; // 6
Solution 2: Recursive C++ 4 lines
int gcd(int a, int b){
    if(b == 0) return a;
    return gcd(b, a % b);
}
Solution 3: Built-in (C++17 std::gcd / __gcd) C++ 2 lines
cout << gcd(12, 18);   // <numeric>, C++17
cout << __gcd(12, 18);

Note: gcd() needs #include <numeric>.

Solution 4: GCD of multiple numbers ★★★★★ C++ 18 lines
int gcd(int a, int b){
    while(b != 0){
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main(){
    int arr[] = {12, 18, 24, 30, 36};
    int len = sizeof(arr) / sizeof(arr[0]);
    int result = arr[0];
    for(int i = 1; i < len; i++){
        result = gcd(result, arr[i]);
    }
    cout << result; // 6
}