Program to find number of ways we can get a number which is sum of nth power of unique numbers in Python

Suppose we have a number x and another number n. We have to find the number of ways we can get x as the sum of nth power of some unique numbers.

So, if the input is like x = 100, n = 2, then the output will be 3 because the possible solutions are:

  • 6² + 8² = 36 + 64 = 100
  • 10² = 100
  • 1² + 3² + 4² + 5² + 7² = 1 + 9 + 16 + 25 + 49 = 100

Algorithm

To solve this problem, we use a recursive backtracking approach ?

  • Start with the smallest number (1) and try to include it or skip it
  • For each number, calculate its nth power
  • If the current sum plus the power equals the target, we found a valid combination
  • If the current sum plus the power is less than the target, continue recursively
  • Count all valid combinations

Example

Let us see the following implementation to get better understanding ?

def solve(x, n, cn=1, cs=0):
    ans = 0
    p = cn ** n
    
    while p + cs < x:
        ans += solve(x, n, cn + 1, p + cs)
        cn = cn + 1
        p = cn ** n
    
    if p + cs == x:
        ans = ans + 1
    
    return ans

x = 100
n = 2
result = solve(x, n)
print(f"Number of ways to get {x} as sum of {n}th powers: {result}")

The output of the above code is ?

Number of ways to get 100 as sum of 2th powers: 3

How It Works

The function solve() takes four parameters:

  • x: Target sum we want to achieve
  • n: The power to which numbers are raised
  • cn: Current number being considered (starts from 1)
  • cs: Current sum accumulated so far

The algorithm explores all possible combinations by trying each number starting from 1. For each number, it calculates the nth power and decides whether to include it in the sum or not.

Alternative Example

Let's try with a different target and power ?

def solve(x, n, cn=1, cs=0):
    ans = 0
    p = cn ** n
    
    while p + cs < x:
        ans += solve(x, n, cn + 1, p + cs)
        cn = cn + 1
        p = cn ** n
    
    if p + cs == x:
        ans = ans + 1
    
    return ans

# Test with different values
test_cases = [(30, 3), (50, 2), (9, 2)]

for x, n in test_cases:
    result = solve(x, n)
    print(f"Ways to get {x} as sum of {n}th powers: {result}")
Ways to get 30 as sum of 3th powers: 1
Ways to get 50 as sum of 2th powers: 2
Ways to get 9 as sum of 2th powers: 1

Conclusion

This recursive backtracking solution efficiently finds all unique ways to express a number as the sum of nth powers of distinct positive integers. The algorithm systematically explores all possible combinations while avoiding duplicates by always considering numbers in ascending order.

Updated on: 2026-03-26T15:43:50+05:30

407 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements