text: Finding LCM of more than two ( or array ) numbers without using GCD | C ++ program to find LCM of array without using GCD . ; Returns LCM of arr [ 0. . n - 1 ] ; Find the maximum value in arr [ ] ; Initialize result ; Find all factors that are present in two or more array elements . int x = 2 ; Current factor . ; To store indexes of all array elements that are divisible by x . ; If there are 2 or more array elements that are divisible by x . ; Reduce all array elements divisible by x . ; Then multiply all reduced array elements ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long int LCM ( int arr [ ] , int n ) { int max_num = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( max_num < arr [ i ] ) max_num = arr [ i ] ; unsigned long long int res = 1 ; while ( x <= max_num ) { vector < int > indexes ; for ( int j = 0 ; j < n ; j ++ ) if ( arr [ j ] % x == 0 ) indexes . push_back ( j ) ; if ( indexes . size ( ) >= 2 ) { for ( int j = 0 ; j < indexes . size ( ) ; j ++ ) arr [ indexes [ j ] ] = arr [ indexes [ j ] ] / x ; res = res * x ; } else x ++ ; } for ( int i = 0 ; i < n ; i ++ ) res = res * arr [ i ] ; return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 10 , 20 , 35 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LCM ( arr , n ) << " STRNEWLINE " ; return 0 ; }