Note:
LCM (Least Common Multiple) is the smallest number that is a multiple of both numbers.
Example: LCM of 12 and 18 is 36.
Formula: LCM(a, b) = (a × b) / GCD(a, b)
int lcm(int a, int b){
int x = a, y = b;
while(y != 0){
int temp = y;
y = x % y;
x = temp;
}
int gcd = x;
return (a / gcd) * b;
}
int main(){
cout << lcm(12, 18); // 36
}
int gcd(int a, int b){
while(b != 0){
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int lcm(int a, int b){
return (a / gcd(a, b)) * b;
}
int main(){
int arr[] = {5, 10, 15, 30};
int len = sizeof(arr) / sizeof(arr[0]);
int result = arr[0];
for(int i = 1; i < len; i++){
result = lcm(result, arr[i]);
}
cout << "LCM " << result; // 30
}