To solve this problem, we need to compute the sum of all divrs of a given integer ( n ). Divrs of a number come in pairs, which allows us to optimize our solution by checking up to the square root of ( n ) instead of the entire range up to ( n ).
Approach
- Edge Case Handling: If ( n ) is non-positive, return 0 since divrs of non-positive integers are either undefined or not considered here.
- Pairwise Divrs: For each integer ( i ) from 1 to the square root of ( n ):
- If ( i ) is a divr of ( n ), add ( i ) to the sum.
- If ( i ) is not the same as ( n/i ) (to avoid double-counting perfect squares), add ( n/i ) to the sum.
- Efficiency: This approach reduces the time complexity to ( O(\sqrt{n}) ), which is much faster than the naive ( O(n) ) approach.
Solution Code
def sum_of_divrs(n):
if n <= 0:
return 0
total = 0
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
total += i
if i != n // i:
total += n // i
return total
Explanation
- Edge Case: The function first checks if ( n ) is non-positive and returns 0 immediately.
- Loop Through Divrs: The loop runs from 1 to ( \sqrt{n} ) (inclusive). For each ( i ):
- If ( i ) divides ( n ), it is added to the sum.
- The corresponding pair ( n/i ) is added only if it is different from ( i ) (to avoid adding the square root twice for perfect squares).
- Result: The total sum of all divrs is returned.
This method efficiently computes the sum of divrs with optimal time complexity, making it suitable for large values of ( n ).
Examples:
- ( sum_of_divrs(6) = 1 + 2 + 3 + 6 = 12 )
- ( sum_of_divrs(4) = 1 + 2 +4 =7 )
- ( sum_of_divrs(12)=1+2+3+4+6+12=28 )
All these examples are handled correctly by the function.
Answer: The function sum_of_divrs as defined above is the solution. The final answer is the code provided.
def sum_of_divrs(n):
if n <= 0:
return 0
total = 0
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
total += i
if i != n // i:
total += n // i
return total


作者声明:本文包含人工智能生成内容。