- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding LCM of more than two (or array) numbers without using GCD in C++
We have an array A, we have to find the LCM of all elements without using the GCD operation. If the array is like {4, 6, 12, 24, 30}, then the LCM will be 120.
The LCM can be calculated easily for two numbers. We have to follow this algorithm to get the LCM.
getLCM(a, b) −
begin if a > b, then m := a, otherwise m := b while true do if m is divisible by both a and b, then return m m := m + 1 done end
Use this function to get LCM of first two numbers of array, then result of LCM will be used to find LCM of next element, thus we can get the result
Example
#include <iostream> using namespace std; int getLCM(int a, int b){ int m; m = (a > b) ? a : b; while(true){ if(m % a == 0 && m % b == 0) return m; m++; } } int getLCMArray(int arr[], int n){ int lcm = getLCM(arr[0], arr[1]); for(int i = 2; i < n; i++){ lcm = getLCM(lcm, arr[i]); } return lcm; } int main() { int arr[] = {4, 6, 12, 24, 30}; int n = sizeof(arr)/sizeof(arr[0]); cout << "LCM of array elements: " << getLCMArray(arr, n); }
Output
LCM of array elements: 120
- Related Articles
- C++ Program for GCD of more than two (or array) numbers?
- C++ Program for GCD 0.of more than two (or array) numbers?
- GCD of more than two (or array) numbers in Python Program
- Python Program for GCD of more than two (or array) numbers
- Java Program for GCD of more than two (or array) numbers
- GCD and LCM of two numbers in Java
- How to calculate GCD of two or more numbers/arrays in JavaScript?
- Program to find GCD or HCF of two numbers in C++
- Program to find GCD or HCF of two numbers using Middle School Procedure in C++
- C++ Program to Find the GCD and LCM of n Numbers
- Finding gcd of two strings in JavaScript
- Find HCF of two numbers without using recursion or Euclidean algorithm in C++
- Find out the GCD of two numbers using while loop in C language
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm
- Find GCD of two numbers

Advertisements