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.
int a = 12, b = 18;
while(b != 0){
int temp = b;
b = a % b;
a = temp;
}
cout << a; // 6
int gcd(int a, int b){
if(b == 0) return a;
return gcd(b, a % b);
}
cout << gcd(12, 18); // <numeric>, C++17
cout << __gcd(12, 18);
Note: gcd() needs #include <numeric>.
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
}