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
def findSum ( arr , n , left , right ) : NEW_LINE INDENT k = right - left + 1 NEW_LINE d = arr [ 1 ] // arr [ 0 ] NEW_LINE ans = arr [ left - 1 ] NEW_LINE if d == 1 : NEW_LINE INDENT ans = ans * d * k NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans * ( d ** k - 1 ) // ( d - 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 ] NEW_LINE queries = 3 NEW_LINE q = [ [ 2 , 4 ] , [ 2 , 6 ] , [ 5 , 8 ] ] NEW_LINE n = len ( arr ) NEW_LINE for i in range ( queries ) : NEW_LINE INDENT print ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT