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 . 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
def LCM ( arr , n ) : NEW_LINE INDENT max_num = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( max_num < arr [ i ] ) : NEW_LINE INDENT max_num = arr [ i ] ; NEW_LINE DEDENT DEDENT res = 1 ; NEW_LINE while ( x <= max_num ) : NEW_LINE INDENT indexes = [ ] ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] % x == 0 ) : NEW_LINE INDENT indexes . append ( j ) ; NEW_LINE DEDENT DEDENT if ( len ( indexes ) >= 2 ) : NEW_LINE INDENT for j in range ( len ( indexes ) ) : NEW_LINE INDENT arr [ indexes [ j ] ] = int ( arr [ indexes [ j ] ] / x ) ; NEW_LINE DEDENT res = res * x ; NEW_LINE DEDENT else : NEW_LINE INDENT x += 1 ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT res = res * arr [ i ] ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 10 , 20 , 35 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( LCM ( arr , n ) ) ; NEW_LINE