From c0ec5a83d52d4dfcb680111f3cec4c5816bd2828 Mon Sep 17 00:00:00 2001 From: Pradyumn Singh Rahar Date: Wed, 19 Oct 2022 19:56:51 +0530 Subject: [PATCH 1/3] Reduced Time Complexity to O(sqrt(n)) --- maths/factors.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/maths/factors.py b/maths/factors.py index e2fdc4063a13..de1c6424db1e 100644 --- a/maths/factors.py +++ b/maths/factors.py @@ -1,3 +1,6 @@ +from math import sqrt + + def factors_of_a_number(num: int) -> list: """ >>> factors_of_a_number(1) @@ -9,7 +12,21 @@ def factors_of_a_number(num: int) -> list: >>> factors_of_a_number(-24) [] """ - return [i for i in range(1, num + 1) if num % i == 0] + facs: list[int] = [] + if num < 1: + return facs + facs.append(1) + if num == 1: + return facs + facs.append(num) + for i in range(2, int(sqrt(num)) + 1): + if num % i == 0: # If i is a factor of num + facs.append(i) + d = num // i # num//i is the other factor of num + if d != i: # If d and i are distinct + facs.append(d) # we have found another factor + facs.sort() + return facs if __name__ == "__main__": From 7bbed7f11eb6bc62bd2d6d023919470eeb7b3c1e Mon Sep 17 00:00:00 2001 From: Pradyumn Singh Rahar Date: Wed, 19 Oct 2022 21:13:11 +0530 Subject: [PATCH 2/3] Added testmod --- maths/factors.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/maths/factors.py b/maths/factors.py index de1c6424db1e..f854a7039e3e 100644 --- a/maths/factors.py +++ b/maths/factors.py @@ -1,5 +1,5 @@ from math import sqrt - +from doctest import testmod def factors_of_a_number(num: int) -> list: """ @@ -28,8 +28,5 @@ def factors_of_a_number(num: int) -> list: facs.sort() return facs - if __name__ == "__main__": - num = int(input("Enter a number to find its factors: ")) - factors = factors_of_a_number(num) - print(f"{num} has {len(factors)} factors: {', '.join(str(f) for f in factors)}") + testmod(name="factors_of_a_number", verbose=True) \ No newline at end of file From f29835134b2ec5bab666763b34be8cb29e089964 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 19 Oct 2022 15:45:00 +0000 Subject: [PATCH 3/3] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- maths/factors.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/maths/factors.py b/maths/factors.py index f854a7039e3e..ae2e5316cf65 100644 --- a/maths/factors.py +++ b/maths/factors.py @@ -1,5 +1,6 @@ -from math import sqrt from doctest import testmod +from math import sqrt + def factors_of_a_number(num: int) -> list: """ @@ -28,5 +29,6 @@ def factors_of_a_number(num: int) -> list: facs.sort() return facs + if __name__ == "__main__": - testmod(name="factors_of_a_number", verbose=True) \ No newline at end of file + testmod(name="factors_of_a_number", verbose=True)