From a29a2a3a0698e936d7275e2c02d3c0c6e478cb4c Mon Sep 17 00:00:00 2001 From: Kenneth P <41343159+ken437@users.noreply.github.com> Date: Fri, 15 May 2020 02:06:51 -0400 Subject: [PATCH] Added file aliquot_sum.py (#1985) * Added file aliquot_sum.py containing a function to find theo * Added parameter type info to aliquot_sum.py * Update maths/aliquot_sum.py Co-authored-by: Christian Clauss * Update maths/aliquot_sum.py Co-authored-by: Christian Clauss * Updated code to raise ValueErrors if input is bad * Fixed logical operators * Removed unnecessary import * Updated aliquot_sum.py * fixed formatting * fixed documentation Co-authored-by: Christian Clauss --- maths/aliquot_sum.py | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 maths/aliquot_sum.py diff --git a/maths/aliquot_sum.py b/maths/aliquot_sum.py new file mode 100644 index 000000000..ac5fa58f4 --- /dev/null +++ b/maths/aliquot_sum.py @@ -0,0 +1,46 @@ +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) if input_num % divisor == 0) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()