forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaliquot_sum.py
48 lines (44 loc) · 1.37 KB
/
aliquot_sum.py
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
defaliquot_sum(input_num: int) ->int:
"""
Finds the aliquot sum of an input integer, where the
aliquot sum of a number n is defined as the sum of all
natural numbers less than n that divide n evenly. For
example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is
a simple O(n) implementation.
@param input_num: a positive integer whose aliquot sum is to be found
@return: the aliquot sum of input_num, if input_num is positive.
Otherwise, raise a ValueError
Wikipedia Explanation: https://en.wikipedia.org/wiki/Aliquot_sum
>>> aliquot_sum(15)
9
>>> aliquot_sum(6)
6
>>> aliquot_sum(-1)
Traceback (most recent call last):
...
ValueError: Input must be positive
>>> aliquot_sum(0)
Traceback (most recent call last):
...
ValueError: Input must be positive
>>> aliquot_sum(1.6)
Traceback (most recent call last):
...
ValueError: Input must be an integer
>>> aliquot_sum(12)
16
>>> aliquot_sum(1)
0
>>> aliquot_sum(19)
1
"""
ifnotisinstance(input_num, int):
raiseValueError("Input must be an integer")
ifinput_num<=0:
raiseValueError("Input must be positive")
returnsum(
divisorfordivisorinrange(1, input_num//2+1) ifinput_num%divisor==0
)
if__name__=="__main__":
importdoctest
doctest.testmod()