Queries to calculate sum of array elements present at every Yth index starting from the index X | Function to Find the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... for all queries ; Iterate over each query ; Stores the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... ; Traverse the array and calculate the sum of the expression ; Update sum ; Update x ; Driver Code
function querySum ( arr , N , Q , M ) { for ( let i = 0 ; i < M ; i ++ ) { let x = Q [ i ] [ 0 ] ; let y = Q [ i ] [ 1 ] ; let sum = 0 ; while ( x < N ) { sum += arr [ x ] ; x += y ; } document . write ( sum + " " ) ; } } let arr = [ 1 , 2 , 7 , 5 , 4 ] ; let Q = [ [ 2 , 1 ] , [ 3 , 2 ] ] ; let N = arr . length ; let M = Q . length ; querySum ( arr , N , Q , M ) ;