Skip to content

Commit 63a40f4

Browse files
authored
Update aliquot_sum.py
1 parent 51ba6ba commit 63a40f4

1 file changed

Lines changed: 38 additions & 38 deletions

File tree

maths/aliquot_sum.py

Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,27 @@
1-
from typing import overload, Tuple
2-
3-
4-
@overload
5-
def aliquot_sum(input_num: int, return_factors: bool = False) -> int: ...
6-
@overload
7-
def aliquot_sum(
8-
input_num: int, return_factors: bool = True
9-
) -> Tuple[int, list[int]]: ...
10-
1+
from __future__ import annotations # Enable modern type hints
2+
from typing import overload
113

124
def aliquot_sum(
135
input_num: int, return_factors: bool = False
14-
) -> int | Tuple[int, list[int]]:
6+
) -> int | tuple[int, list[int]]:
157
"""
168
Calculates the aliquot sum of a positive integer. The aliquot sum is defined as
179
the sum of all proper divisors of a number (all divisors except the number itself).
18-
10+
1911
This implementation uses an optimized O(sqrt(n)) algorithm for efficiency.
20-
12+
2113
Args:
2214
input_num: Positive integer to calculate aliquot sum for
2315
return_factors: If True, returns tuple (aliquot_sum, sorted_factor_list)
24-
16+
2517
Returns:
2618
Aliquot sum if return_factors=False
2719
Tuple (aliquot_sum, sorted_factor_list) if return_factors=True
28-
20+
2921
Raises:
3022
TypeError: If input is not an integer
3123
ValueError: If input is not positive
32-
24+
3325
Examples:
3426
>>> aliquot_sum(15)
3527
9
@@ -41,41 +33,42 @@ def aliquot_sum(
4133
# Validate input type - must be integer
4234
if not isinstance(input_num, int):
4335
raise TypeError("Input must be an integer")
44-
36+
4537
# Validate input value - must be positive
4638
if input_num <= 0:
4739
raise ValueError("Input must be positive integer")
48-
40+
4941
# Special case: 1 has no proper divisors
5042
if input_num == 1:
43+
# Return empty factor list if requested
5144
return (0, []) if return_factors else 0
52-
45+
5346
# Initialize factors list with 1 (always a divisor)
54-
factors = [1]
47+
factors = [1]
5548
total = 1 # Start sum with 1
56-
49+
5750
# Calculate square root as optimization boundary
5851
sqrt_num = int(input_num**0.5)
59-
52+
6053
# Iterate potential divisors from 2 to square root
6154
for divisor in range(2, sqrt_num + 1):
6255
# Check if divisor is a factor
6356
if input_num % divisor == 0:
6457
# Add divisor to factors list
6558
factors.append(divisor)
6659
total += divisor
67-
60+
6861
# Calculate complement (pair factor)
6962
complement = input_num // divisor
70-
63+
7164
# Avoid duplicate for perfect squares
72-
if complement != divisor:
65+
if complement != divisor:
7366
factors.append(complement)
7467
total += complement
75-
68+
7669
# Sort factors for consistent output
7770
factors.sort()
78-
71+
7972
# Return based on return_factors flag
8073
return (total, factors) if return_factors else total
8174

@@ -86,16 +79,16 @@ def classify_number(n: int) -> str:
8679
- Perfect: aliquot sum = number
8780
- Abundant: aliquot sum > number
8881
- Deficient: aliquot sum < number
89-
82+
9083
Args:
9184
n: Positive integer to classify
92-
85+
9386
Returns:
9487
Classification string ("Perfect", "Abundant", or "Deficient")
95-
88+
9689
Raises:
9790
ValueError: If input is not positive
98-
91+
9992
Examples:
10093
>>> classify_number(6)
10194
'Perfect'
@@ -107,14 +100,14 @@ def classify_number(n: int) -> str:
107100
# Validate input
108101
if n <= 0:
109102
raise ValueError("Input must be positive integer")
110-
103+
111104
# Special case: 1 is always deficient
112105
if n == 1:
113106
return "Deficient"
114-
107+
115108
# Calculate aliquot sum (using only the integer version)
116109
s = aliquot_sum(n) # Default returns only integer
117-
110+
118111
# Determine classification
119112
if s == n:
120113
return "Perfect"
@@ -123,15 +116,22 @@ def classify_number(n: int) -> str:
123116

124117
if __name__ == "__main__":
125118
import doctest
126-
119+
127120
# Run embedded doctests for verification
128121
doctest.testmod()
129-
122+
130123
# Additional demonstration examples
131124
print("Aliquot sum of 28:", aliquot_sum(28)) # Perfect number
132-
print("Factors of 28:", aliquot_sum(28, return_factors=True)[1])
125+
126+
# Get factors for 28 with type-safe access
127+
factor_result = aliquot_sum(28, return_factors=True)
128+
# Since we know return_factors=True returns a tuple, we can safely unpack
129+
if isinstance(factor_result, tuple):
130+
_, factors = factor_result
131+
print("Factors of 28:", factors)
132+
133133
print("Classification of 28:", classify_number(28))
134-
134+
135135
# Large number performance test with targeted exception handling
136136
try:
137137
print("\nCalculating aliquot sum for 10^9...")

0 commit comments

Comments
 (0)