Skip to content

Commit 6824429

Browse files
haningrishashermanhui
authored andcommitted
basic_maths input check (TheAlgorithms#4486)
* Prime factor input check * number_of_divisors input check * sum_of_divisors input check
1 parent ad76662 commit 6824429

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

maths/basic_maths.py

+33-4
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,17 @@ def prime_factors(n: int) -> list:
66
"""Find Prime Factors.
77
>>> prime_factors(100)
88
[2, 2, 5, 5]
9+
>>> prime_factors(0)
10+
Traceback (most recent call last):
11+
...
12+
ValueError: Only positive integers have prime factors
13+
>>> prime_factors(-10)
14+
Traceback (most recent call last):
15+
...
16+
ValueError: Only positive integers have prime factors
917
"""
18+
if n <= 0:
19+
raise ValueError("Only positive integers have prime factors")
1020
pf = []
1121
while n % 2 == 0:
1222
pf.append(2)
@@ -24,7 +34,17 @@ def number_of_divisors(n: int) -> int:
2434
"""Calculate Number of Divisors of an Integer.
2535
>>> number_of_divisors(100)
2636
9
37+
>>> number_of_divisors(0)
38+
Traceback (most recent call last):
39+
...
40+
ValueError: Only positive numbers are accepted
41+
>>> number_of_divisors(-10)
42+
Traceback (most recent call last):
43+
...
44+
ValueError: Only positive numbers are accepted
2745
"""
46+
if n <= 0:
47+
raise ValueError("Only positive numbers are accepted")
2848
div = 1
2949
temp = 1
3050
while n % 2 == 0:
@@ -44,7 +64,17 @@ def sum_of_divisors(n: int) -> int:
4464
"""Calculate Sum of Divisors.
4565
>>> sum_of_divisors(100)
4666
217
67+
>>> sum_of_divisors(0)
68+
Traceback (most recent call last):
69+
...
70+
ValueError: Only positive numbers are accepted
71+
>>> sum_of_divisors(-10)
72+
Traceback (most recent call last):
73+
...
74+
ValueError: Only positive numbers are accepted
4775
"""
76+
if n <= 0:
77+
raise ValueError("Only positive numbers are accepted")
4878
s = 1
4979
temp = 1
5080
while n % 2 == 0:
@@ -74,7 +104,6 @@ def euler_phi(n: int) -> int:
74104

75105

76106
if __name__ == "__main__":
77-
print(prime_factors(100))
78-
print(number_of_divisors(100))
79-
print(sum_of_divisors(100))
80-
print(euler_phi(100))
107+
import doctest
108+
109+
doctest.testmod()

0 commit comments

Comments
 (0)