Sum of elements in given range from Array formed by infinitely concatenating given array | Function to find the sum of elements in a given range of an infinite array ; Stores the prefix sum ; Calculate the prefix sum ; Stores the sum of elements from 1 to L - 1 ; Stores the sum of elements from 1 to R ; Print the resultant sum ; Driver Code
function rangeSum ( arr , N , L , R ) { let prefix = new Array ( N + 1 ) ; prefix [ 0 ] = 0 ; for ( let i = 1 ; i <= N ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + arr [ i - 1 ] ; } let leftsum = ( ( L - 1 ) / N ) * prefix [ N ] + prefix [ ( L - 1 ) % N ] ; let rightsum = ( R / N ) * prefix [ N ] + prefix [ R % N ] ; document . write ( rightsum - leftsum ) ; } let arr = [ 5 , 2 , 6 , 9 ] ; let L = 10 , R = 13 ; let N = arr . length ; rangeSum ( arr , N , L , R ) ;