From a3383ce3fd6bc30b01681503a4307df2462c8bd4 Mon Sep 17 00:00:00 2001 From: Pradyumn Singh Rahar Date: Sun, 23 Oct 2022 17:56:40 +0530 Subject: [PATCH] Reduced Time Complexity to O(sqrt(n)) (#7429) * Reduced Time Complexity to O(sqrt(n)) * Added testmod * [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> --- maths/factors.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/maths/factors.py b/maths/factors.py index e2fdc4063..ae2e5316c 100644 --- a/maths/factors.py +++ b/maths/factors.py @@ -1,3 +1,7 @@ +from doctest import testmod +from math import sqrt + + def factors_of_a_number(num: int) -> list: """ >>> factors_of_a_number(1) @@ -9,10 +13,22 @@ 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__": - 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)