forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnum_perfect_squares.py
More file actions
51 lines (37 loc) · 1.1 KB
/
num_perfect_squares.py
File metadata and controls
51 lines (37 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Minimum Perfect Squares Sum
Determine the minimum number of perfect squares that sum to a given integer.
By Lagrange's four-square theorem, the answer is always between 1 and 4.
Reference: https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem
Complexity:
Time: O(sqrt(n))
Space: O(1)
"""
from __future__ import annotations
import math
def num_perfect_squares(number: int) -> int:
"""Find the minimum count of perfect squares that sum to number.
Args:
number: A positive integer.
Returns:
An integer between 1 and 4 representing the minimum count.
Examples:
>>> num_perfect_squares(9)
1
>>> num_perfect_squares(10)
2
>>> num_perfect_squares(12)
3
>>> num_perfect_squares(31)
4
"""
if int(math.sqrt(number)) ** 2 == number:
return 1
while number > 0 and number % 4 == 0:
number /= 4
if number % 8 == 7:
return 4
for i in range(1, int(math.sqrt(number)) + 1):
if int(math.sqrt(number - i**2)) ** 2 == number - i**2:
return 2
return 3