You are given a nonnegative integer
n and an integer
p >= 2. You need to add some
p-th powers (
p=2 means squares,
p=3 means cubes) together to get
n. This is always for any nonnegative
n, but you don't know many
p-th powers (of any positive integer) you'll need.
This is your task: find the minimum number of
p-th powers that can sum to
>>> min_powers(7, 2) 4 # you need at least four squares to add to 7 # Example: (2)^2 + (1)^2 + (1)^2 + (1)^2 = 4 + 1 + 1 + 1 = 7 >>> min_powers(4, 2) 1 # you need at least one square to add to 4 # Example: (2)^2 = 4 >>> min_powers(7, 3) 7 # you need at least seven cubes to add to 7 # Example: 7*(1)^3 = 7 >>> min_powers(23, 3) 9 # you need at least nine cubes to add to 23 # Example: 2*(2)^3 + 7*(1)^2 = 2*8 + 7*1 = 23
A related Wikipedia article on this problem, Waring's problem.
Your code must be a program or a function.
Input is two integers
pin any order. You can assume all inputs are valid (
nis any positive integer,
p >= 2
Output is an integer representing the number of powers needed to sum to
This is code golf, so the shortest program wins., not necessarily the most efficient.
Any and all built-ins are allowed.
As always, if the problem is unclear, please let me know. Good luck and good golfing!