def aliquot_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
"""
if not isinstance(input_num, int):
raise ValueError("Input must be an integer")
if input_num <= 0:
raise ValueError("Input must be positive")
return sum(
divisor for divisor in range(1, input_num // 2 + 1) if input_num % divisor == 0
)
if __name__ == "__main__":
import doctest
doctest.testmod()
正整数 $n$ 的商数和 $s(n)$ 是 $n$ 所有真因数的和,即除了 $n$ 本身之外的所有 $n$ 的因数。也就是说
$$ s(n) = \sum_{d | n, d \neq n} {d} $$
例如,数字 $15$ 的商数和是 $(1 + 3 + 5) = 9$
商数和是数论中一个非常有用的性质,可用于定义
我们循环遍历从 $1$ 到 $[\frac{n} 2]$ 的所有数字,并检查它们是否能整除 $n$,如果能整除,则将其添加为真因数。
我们取 $[\frac{n} 2]$ 作为上限的原因是,偶数的最大可能真因数是 $\frac{n} 2$,如果数字是奇数,则其最大真因数小于 $[\frac{n} 2]$,因此使其成为一个万无一失的上限,在计算上比循环从 $1$ 到 $n$ 更有效率。
我们得到的和就是该数字的商数和