forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactors.py
More file actions
Latest commit
34 lines (30 loc) · 845 Bytes
/
Copy pathfactors.py
File metadata and controls
34 lines (30 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fromdoctestimporttestmod
frommathimportsqrt
deffactors_of_a_number(num: int) ->list:
"""
>>> factors_of_a_number(1)
[1]
>>> factors_of_a_number(5)
[1, 5]
>>> factors_of_a_number(24)
[1, 2, 3, 4, 6, 8, 12, 24]
>>> factors_of_a_number(-24)
[]
"""
facs: list[int] = []
ifnum<1:
returnfacs
facs.append(1)
ifnum==1:
returnfacs
facs.append(num)
foriinrange(2, int(sqrt(num)) +1):
ifnum%i==0: # If i is a factor of num
facs.append(i)
d=num//i# num//i is the other factor of num
ifd!=i: # If d and i are distinct
facs.append(d) # we have found another factor
facs.sort()
returnfacs
if__name__=="__main__":
testmod(name="factors_of_a_number", verbose=True)