Skip to content

Instantly share code, notes, and snippets.

@ibeauregard
Last active March 7, 2022 16:24
Show Gist options
  • Save ibeauregard/66f2db7f5c663683dc68ea501b0221fc to your computer and use it in GitHub Desktop.
Save ibeauregard/66f2db7f5c663683dc68ea501b0221fc to your computer and use it in GitHub Desktop.
Given an integer 'target', return the least number of perfect square numbers that sum to n.
from math import sqrt
def numSquares(target):
squares = [n ** 2 for n in range(1, int(sqrt(target)) + 1)]
level = 0
remainders = {target}
while True:
level += 1
next_remainders = set()
for remainder in remainders:
for square in squares:
if square == remainder:
return level
if square > remainder:
break
next_remainders.add(remainder - square)
remainders = next_remainders
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment