Sum of elements of an AP in the 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 ; NEW_LINE d = arr [ 1 ] - arr [ 0 ] ; NEW_LINE ans = arr [ left - 1 ] * ( k + 1 ) ; NEW_LINE ans = ans + ( d * ( k * ( k + 1 ) ) ) // 2 ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 ] ; NEW_LINE queries = 3 ; NEW_LINE q = [ [ 2 , 4 ] , [ 2 , 6 ] , [ 5 , 6 ] ] ; 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