Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ algorithm to calculate least common multiple for multiple numbers

Tags:

c++

algorithm

lcm

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)?

like image 416
Askener Avatar asked Nov 19 '10 22:11

Askener


People also ask

How do you find the Least Common Multiple of a number in C?

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.

How do you find the LCM of two numbers in C using for loops?

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.


Video Answer


1 Answers

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'; } 
like image 196
Blastfurnace Avatar answered Sep 22 '22 08:09

Blastfurnace