Smallest perfect Cube divisible by all elements of an array | Function to return the gcd of two numbers ; Function to return the lcm of all the elements of the array ; To calculate lcm of two numbers multiply them and divide the result by gcd of both the numbers ; Return the LCM of the array elements ; Function to return the smallest perfect cube divisible by all the elements of arr [ ] ; LCM of all the elements of arr [ ] ; If 2 divides lcm cnt number of times ; Check all the numbers that divide lcm ; Return the answer ; Driver code
function gcd ( a , b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } function lcmOfArray ( arr , n ) { if ( n < 1 ) return 0 ; let lcm = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) lcm = parseInt ( ( lcm * arr [ i ] ) / gcd ( lcm , arr [ i ] ) ) ; return lcm ; } function minPerfectCube ( arr , n ) { let minPerfectCube ; let lcm = lcmOfArray ( arr , n ) ; minPerfectCube = lcm ; let cnt = 0 ; while ( lcm > 1 && lcm % 2 == 0 ) { cnt ++ ; lcm = parseInt ( lcm / 2 ) ; } if ( cnt % 3 == 2 ) minPerfectCube *= 2 ; else if ( cnt % 3 == 1 ) minPerfectCube *= 4 ; let i = 3 ; while ( lcm > 1 ) { cnt = 0 ; while ( lcm % i == 0 ) { cnt ++ ; lcm = parseInt ( lcm / i ) ; } if ( cnt % 3 == 1 ) minPerfectCube *= i * i ; else if ( cnt % 3 == 2 ) minPerfectCube *= i ; i += 2 ; } return minPerfectCube ; } let arr = [ 10 , 125 , 14 , 42 , 100 ] ; let n = arr . length ; document . write ( minPerfectCube ( arr , n ) ) ;