- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Advertisements
To Continue Learning Please Login
Login with Google