Perfect Squares
LeetCode Problem #279 (Medium)
Problem Statement
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum to n.
Testcases
Prerequisite Knowledge
Lagrange's Four-Square Theorem
Statement
Every natural integer can be represented as the sum of four integer squares.
Examples
Legendre's Three-Square Theorem
Statement
Algorithm
Mathematical Approach
According to Lagrange's Four-Square Theorem, any number can be represented as the sum of four square numbers. Applying this theorem in this approach, we perform conditional checks to identify the number of perfect squares that can be used to represent the given number.
Check if the number itself is a perfect square and return 1 if so.
Check if the number can be formed using two perfect square addends.
a. Find the square root of the given number.
b. Iteratively check if the given number subtracted with a perfect square gives another perfect square i.e. the sum of two perfect squares.
c. If the conditions are satisfied, return 2.
Check if the number can be formed using four perfect square addends using Legendre's Three-Square Sum Theorem.
a. Check if the number is a power of 4.
b. Check if the remainder is 7 when divided by 8.
c. If the conditions are satisfied, return 4.
If the prior conditions are not satisfied, then the number can be formed using three perfect square addends. Return 3.
Code
Last updated
Was this helpful?