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

A hyperrectangle is a multi-dimensional rectangle with k dimensions. Each dimension has a length denoted as n1, n2, n3, ..., nm. The hyperrectangle's cells are addressed as (p,q,r,...) and contain a value equivalent to the GCD (Greatest Common Divisor) of their coordinates. Our task is to find the sum of all cell values gcd(p,q,r,...) where 1 ? p ? n1, 1 ? q ? n2, and so on.

Problem Understanding

Given input_arr = [[2, 2], [5, 5]], we need to calculate the sum for two test cases ?

First instance [2, 2]: A 2×2 hyperrectangle

(p,q)   gcd(p,q)
(1,1)      1
(1,2)      1  
(2,1)      1
(2,2)      2
Sum = 1 + 1 + 1 + 2 = 5

Second instance [5, 5]: A 5×5 hyperrectangle

Row 1: gcd(1,1) + gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(1,5) = 1+1+1+1+1 = 5
Row 2: gcd(2,1) + gcd(2,2) + gcd(2,3) + gcd(2,4) + gcd(2,5) = 1+2+1+2+1 = 7
Row 3: gcd(3,1) + gcd(3,2) + gcd(3,3) + gcd(3,4) + gcd(3,5) = 1+1+3+1+1 = 7
Row 4: gcd(4,1) + gcd(4,2) + gcd(4,3) + gcd(4,4) + gcd(4,5) = 1+2+1+4+1 = 9
Row 5: gcd(5,1) + gcd(5,2) + gcd(5,3) + gcd(5,4) + gcd(5,5) = 1+1+1+1+5 = 9
Sum = 5 + 7 + 7 + 9 + 9 = 37

Algorithm Approach

The solution uses the Möbius function principle to efficiently calculate the sum. Instead of computing GCD for each cell individually, we use mathematical optimization ?

  • For each possible GCD value i, calculate how many cells have that GCD
  • Use inclusion-exclusion principle to avoid double counting
  • Multiply the count by the GCD value and sum all results

Implementation

def coeff_find(test_instance, i):
    """Calculate coefficient for GCD value i"""
    value = 1
    for k in test_instance:
        value *= k // i
    return value

def solve(input_arr):
    """Find sum of GCD values in hyperrectangle cells"""
    output = []
    MOD = 10**9 + 7
    
    for test_instance in input_arr:
        min_value = min(test_instance)
        total_value = 0
        temp_dict = {}
        
        # Process from largest to smallest possible GCD
        for i in range(min_value, 0, -1):
            # Count cells divisible by i
            p = coeff_find(test_instance, i)
            
            # Apply inclusion-exclusion principle
            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 % MOD)
    
    return output

# Test the function
test_cases = [[2, 2], [5, 5]]
result = solve(test_cases)
print("Input:", test_cases)
print("Output:", result)
Input: [[2, 2], [5, 5]]
Output: [5, 37]

How It Works

The algorithm works in reverse order (from largest possible GCD to 1) ?

  1. coeff_find() calculates how many cells are divisible by value i
  2. The inclusion-exclusion principle removes overcounting from multiples
  3. Each GCD value i is multiplied by its actual count and added to the total
  4. Result is taken modulo 10? + 7 to handle large numbers

Time Complexity

The time complexity is O(n log n) where n is the minimum dimension size, making it efficient for large hyperrectangles compared to the naive O(n^k) approach.

Conclusion

This solution efficiently computes the sum of GCD values in hyperrectangle cells using mathematical optimization. The inclusion-exclusion principle avoids the need to calculate GCD for each individual cell, providing significant performance improvement.

Updated on: 2026-03-26T13:13:35+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements