Is there a C++ algorithm to calculate the least common multiple for multiple numbers, like lcm(3,6,12)
or lcm(5,7,9,12)
?
Algorithm of LCMStep 1: Initialize the positive integer variables A and B. Step 2: Store the common multiple of A & B into the max variable. Step 3: Validate whether the max is divisible by both variables A and B. Step 4: If max is divisible, display max as the LCM of two numbers.
The test expression of while loop is always true. In each iteration, whether max is perfectly divisible by n1 and n2 is checked. if (min % n1 == 0 && max% n2 == 0) { ... } If this test condition is not true, max is incremented by 1 and the iteration continues until the test expression of the if statement is true.
You can use std::accumulate and some helper functions:
#include <iostream> #include <numeric> int gcd(int a, int b) { for (;;) { if (a == 0) return b; b %= a; if (b == 0) return a; a %= b; } } int lcm(int a, int b) { int temp = gcd(a, b); return temp ? (a / temp * b) : 0; } int main() { int arr[] = { 5, 7, 9, 12 }; int result = std::accumulate(arr, arr + 4, 1, lcm); std::cout << result << '\n'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With