Represent natural number as sum of distinct squares
The problem is to find the largest set S of positive integers such that the sum of the squares of the elements of S is equal to a given number n. For example: 4 = 2² 20 = 4² + 2² 38 = 5² + 3² + 2² 300 = 11² + 8² + 7² + 6² + 4² + 3² + 2² + 1². I have an algorithm that runs in time O(2^(sqrt n) * n) , but it's too slow (every subset of squares). There's an O(n^1.5) -time algorithm based on the canonical dynamic program for subset sum . Here's the recurrence: C(m, k) is the size of the largest subset of 1..k whose squares sum to m C(m, k), m < 0 = -infinity (infeasible) C(0, k) = 0 C(m, 0), m > 0