Finding LCM of more than two ( or array ) numbers 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 . var 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
function LCM ( arr , n ) { var max_num = 0 ; for ( var i = 0 ; i < n ; i ++ ) if ( max_num < arr [ i ] ) max_num = arr [ i ] ; var res = 1 ; while ( x <= max_num ) { var indexes = [ ] ; for ( var j = 0 ; j < n ; j ++ ) if ( arr [ j ] % x == 0 ) indexes . push ( j ) ; if ( indexes . length >= 2 ) { for ( var j = 0 ; j < indexes . length ; j ++ ) arr [ indexes [ j ] ] = arr [ indexes [ j ] ] / x ; res = res * x ; } else x ++ ; } for ( var i = 0 ; i < n ; i ++ ) res = res * arr [ i ] ; return res ; } var arr = [ 1 , 2 , 3 , 4 , 5 , 10 , 20 , 35 ] ; var n = arr . length ; document . write ( LCM ( arr , n ) + " " ) ;