diff --git a/solutions/sum_proper_divisors.py b/solutions/sum_proper_divisors.py new file mode 100644 index 000000000..d0e2c9b4a --- /dev/null +++ b/solutions/sum_proper_divisors.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +A module for calculating the sum of proper divisors of a number. + +Module contents: + - sum_proper_divisors: calculates the sum of proper divisors of a given number. + +Created on Jan 08 2025 +@author: Ibrahim Elmisbah +""" + + +def sum_proper_divisors(n: int) -> int: + """Calculate the sum of proper divisors of a number. + + A proper divisor of a number is a divisor that is less than the number itself. + + Parameters: + n: int, the input number (must be positive) + + Returns -> int: the sum of proper divisors of the number + + Raises: + AssertionError: if the argument is not a positive integer + + >>> sum_proper_divisors(6) + 6 + >>> sum_proper_divisors(10) + 8 + >>> sum_proper_divisors(1) + 0 + """ + assert isinstance(n, int), "Input must be an integer" + assert n > 0, "Input must be a positive integer" + + # Initialize the sum of divisors + total = 0 + + # Check all possible divisors from 1 to n // 2 + for i in range(1, n // 2 + 1): + # If 'i' divides 'n' without a remainder, it is a divisor + if n % i == 0: + total += i # Add 'i' to the total sum of proper divisors + + return total diff --git a/solutions/tests/test_sum_proper_divisors.py b/solutions/tests/test_sum_proper_divisors.py new file mode 100644 index 000000000..566bb2c59 --- /dev/null +++ b/solutions/tests/test_sum_proper_divisors.py @@ -0,0 +1,46 @@ +import unittest + +from ..sum_proper_divisors import sum_proper_divisors + + +class TestSumProperDivisors(unittest.TestCase): + """Tests for the sum_proper_divisors function.""" + + def test_small_number(self): + """It should return the correct sum for a small number.""" + actual = sum_proper_divisors(6) + expected = 6 + self.assertEqual(actual, expected) + + def test_prime_number(self): + """It should return 1 for a prime number.""" + actual = sum_proper_divisors(7) + expected = 1 + self.assertEqual(actual, expected) + + def test_one(self): + """It should return 0 for the number 1.""" + actual = sum_proper_divisors(1) + expected = 0 + self.assertEqual(actual, expected) + + def test_large_number(self): + """It should return the correct sum for a large number.""" + actual = sum_proper_divisors(28) + expected = 28 + self.assertEqual(actual, expected) + + def test_non_integer(self): + """It should raise AssertionError for non-integer input.""" + with self.assertRaises(AssertionError): + sum_proper_divisors(10.5) + + def test_negative_number(self): + """It should raise AssertionError for a negative number.""" + with self.assertRaises(AssertionError): + sum_proper_divisors(-5) + + def test_zero(self): + """It should raise AssertionError for zero input.""" + with self.assertRaises(AssertionError): + sum_proper_divisors(0)