Represent natural number as sum of distinct squares

我怕爱的太早我们不能终老 提交于 2019-11-30 06:52:05

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 = -infinity (infeasible)
C(m, k), m > 0, k > 0 = max(C(m, k-1), C(m - k^2, k-1) + 1)

Compute C(m, k) for all m in 0..n and all k in 0..floor(n^0.5). Return C(n, floor(n^0.5)) for the objective value. To recover the set, trace back the argmaxes.

I was just wondering if this problem reduce to NP? Looks like you have list of integers (squares) less than n (could be generated in O(sqrt(n))) and you're looking for subset sum of size from 1 to sqrt(n) (check all posibilities). If so it should be solvable with knapsack dynamic programming algorithm (but this is pretty naive algorithm and I think it could be improved) in O(n^2) - sqrt(n) of problems to check times sqrt(n) knapsack items count times n knapsack weight.

EDIT: I think with smart backtracking after filling dynamic programming array you could do it in O(n*sqrt(n)).

You can use the recurrence:

T(0, m) = 0
T(n, m) = -Infinity (if n<0 or m<0)
T(n, m) = max(T(n-m*m, m-1)+1, T(n, m-1))

Or, in Python code:

from functools import lru_cache

@lru_cache(100000)
def T(n, m):
    if n<0 or m<0: return (-1000000, 0)
    if n==0: return (0, 0)
    return max((T(n-m*m, m-1)[0]+1, m), T(n, m-1)) 

def squares(n):
    s = int(n**0.5)
    while n>0 and s>0:
        _, factor = T(n, s)
        yield factor**2
        n -= factor**2
        s = factor-1

for x in (4, 20, 38, 300):
    result = list(squares(x))
    print(sum(result), '= sum', result) 

The example you gave (300), can be written with 8 factors as:

300 = 11² + 8² + 7² + 6² + 4² + 3² + 2² + 1²

Other results:

4 = sum [4]
20 = sum [16, 4]
38 = sum [25, 9, 4]
300 = sum [121, 64, 49, 36, 16, 9, 4, 1]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!