Sum of elements of a Geometric Progression ( GP ) in a given range | Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver Code
function findSum ( arr , n , left , right ) { let k = right - left + 1 ; let d = arr [ 1 ] / arr [ 0 ] ; let ans = arr [ left - 1 ] ; if ( d == 1 ) ans = ans * d * k ; else ans = ans * ( Math . pow ( d , k ) - 1 / ( d - 1 ) ) ; return ans ; } let arr = [ 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 ] ; let queries = 3 ; let q = [ [ 2 , 4 ] , [ 2 , 6 ] , [ 5 , 8 ] ] ; let n = arr . length ; for ( let i = 0 ; i < queries ; i ++ ) document . write ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) ;