# Python Program to find out the sum of values in hyperrectangle cells

A hyperrectangle is a rectangle that has k dimensions. Each dimension has a length that can be denoted as n1, n2, n3,....., nm. The hyperrectangle's cells are addressed as (p,q,r,...) and contain a value that is equivalent to gcd of (p,q,r,...). Here 1 <= p <= n1, 1 <= q <= n1, and so on. Our task is to determine the sum of all cell values gcd(p,q,r,...). The result is returned as modulo 10^9 + 7. The indexing is done from 1 to n.

So, if the input is like input_arr = [[2, 2], [5, 5]], then the output will be [5, 37]

There are two instances given to us as input and we have to determine the sum for these two given instances. In each instance, the hyperrectangles are 4x4 2-dimensional rectangles, and the lengths are given. The address (p,q) and the gcd(p,q) will be like this −

(p,q)   value   gcd(p,q)
(1, 1)  (1, 2)  1 1
(2, 1)  (2, 2)  1 2

Sum of gcds = 1 + 1 + 1 + 2 = 5

In the second instance −

(p,q)  value                gcd(p,q) sum(gcd of row i)
(1, 1) (1, 2) (1, 3) (1, 4) (1, 5)   1 1 1 1 1 = 5
(2, 1) (2, 2) (2, 3) (2, 4) (2, 5)   1 2 1 2 1 = 7
(3, 1) (3, 2) (3, 3) (3, 4) (3, 5)   1 1 3 1 1 = 7
(4, 1) (4, 2) (4, 3) (4, 4) (4, 5)   1 2 1 4 1 = 9
(5, 1) (5, 2) (5, 3) (5, 4) (5, 5)   1 1 1 1 5 = 9

Sum of gcds = 5 + 7 + 7 + 9 + 9 = 37

To solve this, we will follow these steps −

• Define a function coeff_find() . This will take test_instance, i

• value := 1
• for each k in test_instance, do
• value := value * float value of (k / i)
• return value
• From the main method/function, do the following −
• output := a new list
• for each test_instance in input_arr, do
• min_value := minimum of test_instance
• total_value := 0
• temp_dict := a new map
• for i in range min_value to 0, decrease by 1, do
• p := coeff_find(test_instance, i)
• q := i
• while q <= min_value, do
• q := q + i
• if q is present in temp_dict, then
• p := p - temp_dict[q]
• temp_dict[i] := p
• total_value := total_value + temp_dict[i]*i
• add (total_value mod (10^9 + 7)) at the end of the list output
• return output

## Example

Let us see the following implementation to get better understanding −

Live Demo

def coeff_find(test_instance, i):
value = 1
for k in test_instance:
value *= k // i
return value
def solve(input_arr):
output = []
for test_instance in input_arr:
min_value = min(test_instance)
total_value = 0
temp_dict = {}
for i in range(min_value, 0, -1):
p = coeff_find(test_instance, i)
q = i
while q <= min_value:
q += i
if q in temp_dict:
p -= temp_dict[q]
temp_dict[i] = p
total_value += temp_dict[i]*i
output.append(total_value % (10**9 + 7))
return output
print(solve([[2, 2], [5, 5]]))

## Input

[[2, 2], [5, 5]]

## Output

[5, 37]

Updated on: 18-May-2021

110 Views