Suppose we have a number x and another number n. We have to find number of ways we can get x as 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 possible solutions are 6^2 + 8^2, 10^2 and 1^2 + 3^2 + 4^2 + 5^2 + 7^2.
To solve this, we will follow these steps −
- ans := 0
- Define a method called solve() this will take four parameters x, n, cn and cs, the initial
- values for cs = 0, cn = 1
- p := cn^n
- while p + cs < x, do
- ans := ans + solve(x, n, cn + 1, p + cs)
- cn := cn + 1
- p := cn^n
- if p + cs is same as x, then
- ans := ans + 1
- return ans
Example
Let us see the following implementation to get better understanding −
from math import pow def solve(x, n, cn = 1, cs = 0): ans = 0 p = pow(cn, n) while p + cs < x: ans += solve(x, n, cn + 1, p + cs) cn = cn + 1 p = pow(cn, n) if p + cs == x: ans = ans + 1 return ans x = 100 n = 2 print(solve(x, n))
Input
100, 2
Output
3