Math Fundamentals18 sections · 814 units
Open in Course

Problem - Perfect Squares (Third problem)

LeetCode 279

Given a positive integer nn, find the minimum number of perfect square numbers that sum to nn. For example, n=12n = 12 can be written as 4+4+44 + 4 + 4 (three squares) or 9+1+1+19 + 1 + 1 + 1 (four squares). The answer is 33.

This is a dynamic programming problem, but logarithms appear when computing perfect squares. How many perfect squares are there up to nn? About n\sqrt{n}, and log2(n)=12log2(n)\log_2(\sqrt{n}) = \frac{1}{2} \log_2(n).

Before reading the solution, think about this: how would you find all perfect squares up to nn? And how does the logarithm relate to the number of bits in nn?