Given an n integer (n >= 1), and a number k, return all possible ways to write n as kth power different integers. For instance, if n = 100 and k = 2:
100 = 1**2 + 3**2 + 4**2 + 5**2 + 7**2
= 6**2 + 8**2
= 10**2
or if k = 3:
100 = 1**3 + 2**3 + 3**3 + 4**3
So program(100,2)
returns something like [(2, [1, 3, 4, 5, 7]), (2, [6, 8]), (2, [10])]
,
and program(100,3)
[(3, [1, 2, 3, 4])]
.
Everything works fine, as long as the input n is small, or k is "big" (>=3). My approach was to first get a list of all integers, whose kth power is <= n.
def possible_powers(n,k):
arr,i = [],1
while i**k <= n:
arr.append(i)
i += 1
return arr
Then (and here's the mistake), I created all subsets of this list (as lists):
def subsets(L):
subsets = [[]]
for i in L:
subsets += [subset+[i] for subset in subsets]
return subsets
And finally I cycled through all these subsets, raising each element to the kth power and adding them together, selecting only the ones that add up to n.
def kth_power_sum(arr,k):
return sum([i**k for i in arr])
def solutions(n,k):
return [(k,i) for i in subsets(possible_powers(n,k)) if kth_power_sum(i,k) == n]
I know the problem is with the subset-creation, but I have no clue how to optimize this. Like, if I try solutions(1000,2), it creates a large set, which takes up more than 4GB memory. My guess would be to sieve out a few subsets, but that wouldn't help much, unless I have a very efficient sieve.
Any help is greatly appreciated. If something isn't clear, or I made a mistake in posting this, please tell me.