

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- GCD of more than two (or array) numbers in Python Program
- C++ Program for GCD of more than two (or array) numbers?
- Python Program for GCD of more than two (or array) numbers
- Java Program for GCD of more than two (or array) numbers
- C++ Program for GCD 0.of more than two (or array) numbers?
- GCD and LCM of two numbers in Java
- Find LCM of two numbers
- Finding gcd of two strings in JavaScript
- Find GCD of two numbers
- Program to find GCD or HCF of two numbers in C++
- C++ Program to Find the GCD and LCM of n Numbers
- Java program to find the GCD or HCF of two numbers
- LCM of an array of numbers in Java
- Program to find GCD or HCF of two numbers using Middle School Procedure in C++
- Java Program to Find LCM of two Numbers
Advertisements