Skip to content

Commit 9869c01

Browse files
authored
Update aliquot_sum.py
1 parent 9917456 commit 9869c01

1 file changed

Lines changed: 39 additions & 35 deletions

File tree

maths/aliquot_sum.py

Lines changed: 39 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,21 @@ def aliquot_sum(
44
"""
55
Calculates the aliquot sum of a positive integer. The aliquot sum is defined as
66
the sum of all proper divisors of a number (all divisors except the number itself).
7-
7+
88
This implementation uses an optimized O(sqrt(n)) algorithm for efficiency.
9-
9+
1010
Args:
1111
input_num: Positive integer to calculate aliquot sum for
1212
return_factors: If True, returns tuple (aliquot_sum, sorted_factor_list)
13-
13+
1414
Returns:
1515
Aliquot sum if return_factors=False
1616
Tuple (aliquot_sum, sorted_factor_list) if return_factors=True
17-
17+
1818
Raises:
1919
TypeError: If input is not an integer
2020
ValueError: If input is not positive
21-
21+
2222
Examples:
2323
>>> aliquot_sum(15)
2424
9
@@ -30,42 +30,42 @@ def aliquot_sum(
3030
# Validate input type - must be integer
3131
if not isinstance(input_num, int):
3232
raise TypeError("Input must be an integer")
33-
33+
3434
# Validate input value - must be positive
3535
if input_num <= 0:
3636
raise ValueError("Input must be positive integer")
37-
37+
3838
# Special case: 1 has no proper divisors
3939
if input_num == 1:
4040
# Return empty factor list if requested
4141
return (0, []) if return_factors else 0
42-
42+
4343
# Initialize factors list with 1 (always a divisor)
44-
factors = [1]
44+
factors = [1]
4545
total = 1 # Start sum with 1
46-
46+
4747
# Calculate square root as optimization boundary
4848
sqrt_num = int(input_num**0.5)
49-
49+
5050
# Iterate potential divisors from 2 to square root
5151
for divisor in range(2, sqrt_num + 1):
5252
# Check if divisor is a factor
5353
if input_num % divisor == 0:
5454
# Add divisor to factors list
5555
factors.append(divisor)
5656
total += divisor
57-
57+
5858
# Calculate complement (pair factor)
5959
complement = input_num // divisor
60-
60+
6161
# Avoid duplicate for perfect squares
62-
if complement != divisor:
62+
if complement != divisor:
6363
factors.append(complement)
6464
total += complement
65-
65+
6666
# Sort factors for consistent output
6767
factors.sort()
68-
68+
6969
# Return based on return_factors flag
7070
return (total, factors) if return_factors else total
7171

@@ -76,16 +76,16 @@ def classify_number(n: int) -> str:
7676
- Perfect: aliquot sum = number
7777
- Abundant: aliquot sum > number
7878
- Deficient: aliquot sum < number
79-
79+
8080
Args:
8181
n: Positive integer to classify
82-
82+
8383
Returns:
8484
Classification string ("Perfect", "Abundant", or "Deficient")
85-
85+
8686
Raises:
8787
ValueError: If input is not positive
88-
88+
8989
Examples:
9090
>>> classify_number(6)
9191
'Perfect'
@@ -97,14 +97,14 @@ def classify_number(n: int) -> str:
9797
# Validate input
9898
if n <= 0:
9999
raise ValueError("Input must be positive integer")
100-
100+
101101
# Special case: 1 is always deficient
102102
if n == 1:
103103
return "Deficient"
104-
105-
# Calculate aliquot sum (must be int only)
106-
s = aliquot_sum(n) # type: ignore[assignment]
107-
104+
105+
# Calculate aliquot sum (explicitly request integer-only result)
106+
s = aliquot_sum(n, return_factors=False)
107+
108108
# Determine classification
109109
if s == n:
110110
return "Perfect"
@@ -113,27 +113,31 @@ def classify_number(n: int) -> str:
113113

114114
if __name__ == "__main__":
115115
import doctest
116-
116+
117117
# Run embedded doctests for verification
118118
doctest.testmod()
119-
119+
120120
# Additional demonstration examples
121121
print("Aliquot sum of 28:", aliquot_sum(28)) # Perfect number
122-
123-
# Handle tuple return type safely
124-
result = aliquot_sum(28, True)
125-
if isinstance(result, tuple):
126-
print("Factors of 28:", result[1])
127-
122+
123+
# Get factors for 28 (using explicit tuple handling)
124+
factor_result = aliquot_sum(28, True)
125+
# Since we requested factors, result is tuple (sum, factors)
126+
if isinstance(factor_result, tuple):
127+
print("Factors of 28:", factor_result[1])
128+
128129
print("Classification of 28:", classify_number(28))
129-
130-
# Large number performance test (catch specific errors)
130+
131+
# Large number performance test with targeted exception handling
131132
try:
132133
print("\nCalculating aliquot sum for 10^9...")
133134
print("Result:", aliquot_sum(10**9)) # 1497558336
134135
except (TypeError, ValueError) as e:
136+
# Handle input-related errors
135137
print(f"Input error: {e}")
136138
except MemoryError:
139+
# Handle potential memory issues with large numbers
137140
print("Memory error: Number too large")
138141
except OverflowError:
142+
# Handle numeric overflow
139143
print("Overflow error: Calculation too large")

0 commit comments

Comments
 (0)