Skip to content

Commit 8fd06ef

Browse files
Create minimums_squares_to_represent_a_number.py (TheAlgorithms#7595)
* Create minimums_squares_to_represent_a_number.py added a dynamic programming approach of finding the minimum number of square to represent a number. eg : 25 = 5*5 37 = 6*6 + 1*1 21 = 4*4 + 2*2 + 1*1 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update and rename minimums_squares_to_represent_a_number.py to minimum_squares_to_represent_a_number.py updated the code * Update minimum_squares_to_represent_a_number.py I have added the appropriate checks for 0 and 12.34. It would be great if you could suggest a name for the dp array * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update minimum_squares_to_represent_a_number.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update minimum_squares_to_represent_a_number.py updated * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update minimum_squares_to_represent_a_number.py updated * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 9390565 commit 8fd06ef

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import math
2+
import sys
3+
4+
5+
def minimum_squares_to_represent_a_number(number: int) -> int:
6+
"""
7+
Count the number of minimum squares to represent a number
8+
>>> minimum_squares_to_represent_a_number(25)
9+
1
10+
>>> minimum_squares_to_represent_a_number(37)
11+
2
12+
>>> minimum_squares_to_represent_a_number(21)
13+
3
14+
>>> minimum_squares_to_represent_a_number(58)
15+
2
16+
>>> minimum_squares_to_represent_a_number(-1)
17+
Traceback (most recent call last):
18+
...
19+
ValueError: the value of input must not be a negative number
20+
>>> minimum_squares_to_represent_a_number(0)
21+
1
22+
>>> minimum_squares_to_represent_a_number(12.34)
23+
Traceback (most recent call last):
24+
...
25+
ValueError: the value of input must be a natural number
26+
"""
27+
if number != int(number):
28+
raise ValueError("the value of input must be a natural number")
29+
if number < 0:
30+
raise ValueError("the value of input must not be a negative number")
31+
if number == 0:
32+
return 1
33+
answers = [-1] * (number + 1)
34+
answers[0] = 0
35+
for i in range(1, number + 1):
36+
answer = sys.maxsize
37+
root = int(math.sqrt(i))
38+
for j in range(1, root + 1):
39+
current_answer = 1 + answers[i - (j**2)]
40+
answer = min(answer, current_answer)
41+
answers[i] = answer
42+
return answers[number]
43+
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
48+
doctest.testmod()

0 commit comments

Comments
 (0)