text: Smallest perfect Cube divisible by all elements of an array | C ++ implementation of the approach ; 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long int NEW_LINE ll gcd ( ll a , ll b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } ll lcmOfArray ( int arr [ ] , int n ) { if ( n < 1 ) return 0 ; ll lcm = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) lcm = ( lcm * arr [ i ] ) / gcd ( lcm , arr [ i ] ) ; return lcm ; } int minPerfectCube ( int arr [ ] , int n ) { ll minPerfectCube ; ll lcm = lcmOfArray ( arr , n ) ; minPerfectCube = ( long long ) lcm ; int cnt = 0 ; while ( lcm > 1 && lcm % 2 == 0 ) { cnt ++ ; lcm /= 2 ; } if ( cnt % 3 == 2 ) minPerfectCube *= 2 ; else if ( cnt % 3 == 1 ) minPerfectCube *= 4 ; int i = 3 ; while ( lcm > 1 ) { cnt = 0 ; while ( lcm % i == 0 ) { cnt ++ ; lcm /= i ; } if ( cnt % 3 == 1 ) minPerfectCube *= i * i ; else if ( cnt % 3 == 2 ) minPerfectCube *= i ; i += 2 ; } return minPerfectCube ; } int main ( ) { int arr [ ] = { 10 , 125 , 14 , 42 , 100 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minPerfectCube ( arr , n ) ; return 0 ; }