TheAlgorithms-Python
48 строк · 1.4 Кб
1def aliquot_sum(input_num: int) -> int:
2"""
3Finds the aliquot sum of an input integer, where the
4aliquot sum of a number n is defined as the sum of all
5natural numbers less than n that divide n evenly. For
6example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is
7a simple O(n) implementation.
8@param input_num: a positive integer whose aliquot sum is to be found
9@return: the aliquot sum of input_num, if input_num is positive.
10Otherwise, raise a ValueError
11Wikipedia Explanation: https://en.wikipedia.org/wiki/Aliquot_sum
12
13>>> aliquot_sum(15)
149
15>>> aliquot_sum(6)
166
17>>> aliquot_sum(-1)
18Traceback (most recent call last):
19...
20ValueError: Input must be positive
21>>> aliquot_sum(0)
22Traceback (most recent call last):
23...
24ValueError: Input must be positive
25>>> aliquot_sum(1.6)
26Traceback (most recent call last):
27...
28ValueError: Input must be an integer
29>>> aliquot_sum(12)
3016
31>>> aliquot_sum(1)
320
33>>> aliquot_sum(19)
341
35"""
36if not isinstance(input_num, int):
37raise ValueError("Input must be an integer")
38if input_num <= 0:
39raise ValueError("Input must be positive")
40return sum(
41divisor for divisor in range(1, input_num // 2 + 1) if input_num % divisor == 0
42)
43
44
45if __name__ == "__main__":
46import doctest
47
48doctest.testmod()
49