Finding LCM of more than two ( or array ) numbers without using GCD | Java 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
import java . util . Vector ; class GFG { static long 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 ] ; } } long res = 1 ; while ( x <= max_num ) { Vector < Integer > indexes = new Vector < > ( ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] % x == 0 ) { indexes . add ( indexes . size ( ) , j ) ; } } if ( indexes . size ( ) >= 2 ) { for ( int j = 0 ; j < indexes . size ( ) ; j ++ ) { arr [ indexes . get ( j ) ] = arr [ indexes . get ( j ) ] / x ; } res = res * x ; } else { x ++ ; } } for ( int i = 0 ; i < n ; i ++ ) { res = res * arr [ i ] ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 10 , 20 , 35 } ; int n = arr . length ; System . out . println ( LCM ( arr , n ) ) ; } }