# Program to find out the sum of evenly spaced elements in an array in Python

PythonServer Side ProgrammingProgramming

Suppose, there is an array 'nums' of size n containing positive integers. We have another array 'queries' that contain integer pairs (pi, qi). For every query in the array queries, the answer will be the sum of numbers in the array nums[j] where pi <= j < n and (j - pi) is divisible by qi. We have to return the answer of all such queries, and if it is a large value, we return the answer modulo 10^9 + 7.

So, if the input is like nums = [2, 3, 4, 5, 6, 7, 8, 9, 10], queries = [(2, 5), (7, 3), (6, 4)], then the output will be [13, 9, 8].

To solve this, we will follow these steps −

• A := nums

• Q := queries

• n := length of nums

• M := 10^9 + 7

• m := integer value of (n ^ 0.5) + 2

• P := a new list containing the list A m times

• for i in range 1 to m, do

• for j in range n-1 to -1, decrease by 1, do

• if i+j < n, then

• P[i, j] := (P[i, j]+P[i, i+j]) modulo M

• for each value b, k in Q, do

• if k < m, then

• return [value from index P[k, b]]

• otherwise

• return [sum(A[b to k]) modulo M]

## Example

Let us see the following implementation to get better understanding −

def solve(A, Q):
n, M = len(A), 10**9+7
m = int(n**0.5)+2
P = [A[:] for _ in range(m)]
for i in range(1,m):
for j in range(n-1,-1,-1):
if i+j < n:
P[i][j] = (P[i][j]+P[i][i+j]) % M
return [P[k][b] if k < m else sum(A[b::k]) % M for b, k in Q]

print(solve([2, 3, 4, 5, 6, 7, 8, 9, 10], [(2, 5), (7, 3), (6, 4)]))

## Input

[2, 3, 4, 5, 6, 7, 8, 9, 10], [(2, 5), (7, 3), (6, 4)]


## Output

[13, 9, 8]
Published on 08-Oct-2021 07:33:29