Queries to calculate sum of array elements present at every Yth index starting from the index X | Java program for the above approach ; 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
import java . util . * ; class GFG { static void querySum ( int arr [ ] , int N , int Q [ ] [ ] , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int x = Q [ i ] [ 0 ] ; int y = Q [ i ] [ 1 ] ; int sum = 0 ; while ( x < N ) { sum += arr [ x ] ; x += y ; } System . out . print ( sum + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 7 , 5 , 4 } ; int Q [ ] [ ] = { { 2 , 1 } , { 3 , 2 } } ; int N = arr . length ; int M = Q . length ; querySum ( arr , N , Q , M ) ; } }