From 453f95db9b2e295609fbc1fd5c4b37aad9298c4a Mon Sep 17 00:00:00 2001 From: JatinR05 <71865805+JatinR05@users.noreply.github.com> Date: Mon, 24 Oct 2022 12:24:31 +0530 Subject: [PATCH] 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 --- .../minimums_squares_to_represent_a_number.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 dynamic_programming/minimums_squares_to_represent_a_number.py diff --git a/dynamic_programming/minimums_squares_to_represent_a_number.py b/dynamic_programming/minimums_squares_to_represent_a_number.py new file mode 100644 index 000000000000..71ef804eac31 --- /dev/null +++ b/dynamic_programming/minimums_squares_to_represent_a_number.py @@ -0,0 +1,35 @@ +import math,sys + +def minimum_squares_to_represent_a_number(number: int) -> int: + """ + Count the number of minimum squares to represent a number + >>> minimum_squares_to_represent_a_number(25) + 1 + >>> minimum_squares_to_represent_a_number(37) + 2 + >>> minimum_squares_to_represent_a_number(21) + 3 + >>> minimum_squares_to_represent_a_number(58) + 2 + >>> minimum_squares_to_represent_a_number(-1) + Traceback (most recent call last): + ... + ValueError: the value of input must be positive + """ + if number < 0: + raise ValueError("the value of input must be positive") + dp = [-1 for x in range(number+1)] + dp[0] = 0 + for i in range(1,number+1): + ans = sys.maxsize + root = int(math.sqrt(i)) + for j in range(1,root+1): + currAns = 1 + dp[i-(j**2)] + ans = min(ans,currAns) + dp[i] = ans + return dp[number] + +if __name__ == "__main__": + import doctest + + doctest.testmod()