Check if sum of divisors of two numbers are same in Python

Sometimes we need to check whether two numbers have the same sum of divisors. This problem involves finding all proper divisors (excluding the number itself) of both numbers and comparing their sums.

For example, if we have p = 559 and q = 703:

  • Divisors of 559: 1, 13, 43 (sum = 57)
  • Divisors of 703: 1, 19, 37 (sum = 57)

Since both sums equal 57, the numbers have the same divisor sum.

Algorithm

To solve this efficiently, we'll:

  • Create a function to calculate the sum of proper divisors
  • Iterate only up to the square root of the number for efficiency
  • For each divisor i found, add both i and n/i to the sum
  • Compare the divisor sums of both numbers

Implementation

def divSum(n):
    total = 1  # 1 is always a divisor
    i = 2
    
    while i * i <= n:
        if n % i == 0:
            total += i  # Add the divisor
            if i != n // i:  # Avoid counting the square root twice
                total += n // i  # Add the corresponding divisor
        i += 1
    
    return total

def solve(p, q):
    return divSum(p) == divSum(q)

# Test with the example
p = 559
q = 703
result = solve(p, q)
print(f"Sum of divisors of {p}: {divSum(p)}")
print(f"Sum of divisors of {q}: {divSum(q)}")
print(f"Are the sums equal? {result}")
Sum of divisors of 559: 57
Sum of divisors of 703: 57
Are the sums equal? True

How It Works

The algorithm works by:

  1. Starting with 1: Since 1 is a divisor of every positive integer
  2. Checking up to ?n: For each number i that divides n, both i and n/i are divisors
  3. Avoiding duplicates: When i² = n, we only count i once
  4. Comparing sums: Return True if both numbers have equal divisor sums

Testing with Different Numbers

def divSum(n):
    total = 1
    i = 2
    
    while i * i <= n:
        if n % i == 0:
            total += i
            if i != n // i:
                total += n // i
        i += 1
    
    return total

def solve(p, q):
    return divSum(p) == divSum(q)

# Test cases
test_cases = [(559, 703), (6, 28), (12, 18)]

for p, q in test_cases:
    sum_p = divSum(p)
    sum_q = divSum(q)
    result = solve(p, q)
    print(f"{p}: divisor sum = {sum_p}")
    print(f"{q}: divisor sum = {sum_q}")
    print(f"Equal sums? {result}")
    print("-" * 20)
559: divisor sum = 57
703: divisor sum = 57
Equal sums? True
--------------------
6: divisor sum = 6
28: divisor sum = 28
Equal sums? False
--------------------
12: divisor sum = 16
18: divisor sum = 21
Equal sums? False
--------------------

Conclusion

This solution efficiently finds the sum of proper divisors by iterating only up to the square root of each number. The algorithm has O(?n) time complexity, making it suitable for checking divisor sum equality between two numbers.

Updated on: 2026-03-25T14:28:51+05:30

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements