Smallest power of 2 which is greater than or equal to sum of array elements | Function to find the nearest power of 2 ; The number ; If already a power of 2 ; Find the next power of 2 ; Function to find the memory used ; Sum of array ; Traverse and find the sum of array ; Function call to find the nearest power of 2 ; Driver Code
function nextPowerOf2 ( n ) { let p = 1 ; if ( n && ! ( n & ( n - 1 ) ) ) return n ; while ( p < n ) p <<= 1 ; return p ; } function memoryUsed ( arr , n ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; let nearest = nextPowerOf2 ( sum ) ; return nearest ; } let arr = [ 1 , 2 , 3 , 2 ] ; let n = arr . length ; document . write ( memoryUsed ( arr , n ) ) ;