Skip to content

Commit a3383ce

Browse files
Reduced Time Complexity to O(sqrt(n)) (TheAlgorithms#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>
1 parent b092f99 commit a3383ce

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

Diff for: maths/factors.py

+20-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
from doctest import testmod
2+
from math import sqrt
3+
4+
15
def factors_of_a_number(num: int) -> list:
26
"""
37
>>> factors_of_a_number(1)
@@ -9,10 +13,22 @@ def factors_of_a_number(num: int) -> list:
913
>>> factors_of_a_number(-24)
1014
[]
1115
"""
12-
return [i for i in range(1, num + 1) if num % i == 0]
16+
facs: list[int] = []
17+
if num < 1:
18+
return facs
19+
facs.append(1)
20+
if num == 1:
21+
return facs
22+
facs.append(num)
23+
for i in range(2, int(sqrt(num)) + 1):
24+
if num % i == 0: # If i is a factor of num
25+
facs.append(i)
26+
d = num // i # num//i is the other factor of num
27+
if d != i: # If d and i are distinct
28+
facs.append(d) # we have found another factor
29+
facs.sort()
30+
return facs
1331

1432

1533
if __name__ == "__main__":
16-
num = int(input("Enter a number to find its factors: "))
17-
factors = factors_of_a_number(num)
18-
print(f"{num} has {len(factors)} factors: {', '.join(str(f) for f in factors)}")
34+
testmod(name="factors_of_a_number", verbose=True)

0 commit comments

Comments
 (0)