Minimum Perfect Squares to Sum to Target
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Tests understanding of number theory and optimal algorithms for decomposing integers into sums of perfect squares.
Problem Statement
You are given a positive integer n. Your task is to find the smallest quantity of perfect square integers (1, 4, 9, 16, 25, ...) that add up to exactly n.
A perfect square is an integer that equals some integer multiplied by itself. For instance, 1 = 1×1, 4 = 2×2, 9 = 3×3, and so on.
Implement the following function:
def fewest_squares(n: int) -> int:
The function should return the minimum count of perfect squares needed to sum to n. You may use the same perfect square multiple times.
Constraints
1 ≤ n ≤ 10^5- Your solution should run in O(√n) time or better
Notes
- Every positive integer can be expressed as a sum of at most four perfect squares (this is a known mathematical theorem)
- When
nitself is a perfect square, the answer is obviously 1 - Consider whether mathematical properties can help avoid exhaustive search
Examples
Example 1
Input: fewest_squares(12)
Output: 3
Example 2
Input: fewest_squares(13)
Output: 2
Hints
Hint 1
Check if the number itself is a perfect square first—that immediately gives you an answer of 1
Hint 2
Try checking if the number can be written as the sum of exactly two perfect squares by iterating through possible first squares
Hint 3
Use Legendre's three-square theorem: a positive integer can be expressed as a sum of three squares if and only if it is NOT of the form 4^a × (8b + 7)
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Rather than using dynamic programming or breadth-first search (which would take O(n√n) time), we exploit mathematical theorems to determine the answer in O(√n) time.
The key insight is that every positive integer can be represented as a sum of at most four perfect squares. We systematically check whether fewer squares suffice:
- One square: Check if
nis a perfect square by computing its integer square root and verifying the result - Two squares: Iterate through all possible values for the first square
a²wherearanges from 0 to √n, and check if the remaindern - a²is also a perfect square - Four squares: Apply Legendre's three-square theorem, which states that a number requires exactly four squares if and only if it has the form
4^k × (8m + 7)for non-negative integers k and m. To check this, repeatedly divide by 4 while possible, then check if the result is congruent to 7 modulo 8 - Three squares: If none of the above conditions hold, exactly three squares are needed
Why This Works
Mathematical theorems guarantee these cases are exhaustive:
- Lagrange's four-square theorem ensures no number needs more than four squares
- Legendre's three-square theorem precisely characterizes which numbers need four versus three squares
- Our explicit checks for one and two squares ensure we return the minimum
The use of math.isqrt ensures exact integer arithmetic without floating-point errors.
Complexity
- Time complexity: O(√n)
- The perfect square check is O(1)
- The two-square loop runs at most √n + 1 iterations
- Dividing out factors of 4 takes O(log n) iterations
- Space complexity: O(1)
- Only a constant amount of extra storage is used
Solution Code
from math import isqrt
def fewest_squares(n: int) -> int:
# Check if n is already a perfect square
root = isqrt(n)
if root * root == n:
return 1
# Check if n can be expressed as sum of two perfect squares
for a in range(root + 1):
remainder = n - a * a
b = isqrt(remainder)
if b * b == remainder:
return 2
# Apply Legendre's theorem: check if n = 4^k * (8m + 7)
# If so, exactly 4 squares are needed
temp = n
while temp % 4 == 0:
temp //= 4
if temp % 8 == 7:
return 4
# Otherwise, 3 squares suffice
return 3