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
function findSum ( arr , n , left , right ) { let k = right - left ; let d = arr [ 1 ] - arr [ 0 ] ; let ans = arr [ left - 1 ] * ( k + 1 ) ; ans = ans + ( d * ( k * ( k + 1 ) ) ) / 2 ; return ans ; } let arr = [ 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 ] ; let queries = 3 ; let q = [ [ 2 , 4 ] , [ 2 , 6 ] , [ 5 , 6 ] ] ; let n = arr . length ; for ( let i = 0 ; i < queries ; i ++ ) document . write ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) + " " ) ;