To solve this problem, we need to compute the sum of all proper divrs of a given number ( n ), where a proper divr is a number that divides ( n ) exactly and is less than ( n ) itself.
Approach
The key insight to efficiently compute the sum of proper divrs is to leverage the properties of divrs:
- For any number ( n ), divrs come in pairs ((i, n/i)) where ( i \leq \sqrt{n} ).
- We only need to check divrs up to ( \sqrt{n} ) to avoid redundant calculations.
- Handle edge cases: if ( n \leq 1 ), there are no proper divrs, so the sum is 0.
- Include 1 as a proper divr (since it divides all positive integers and is less than ( n ) for ( n >1 )).
- For each divr ( i ) found, add both ( i ) and ( n/i ) to the sum (unless they are the same, to avoid double-counting perfect squares).
Solution Code
def sum_divrs(n):
if n <= 1:
return 0
total = 1 # 1 is a proper divr for all n > 1
sqrt_n = int(n ** 0.5)
for i in range(2, sqrt_n + 1):
if n % i == 0:
total += i
counterpart = n // i
if counterpart != i:
total += counterpart
return total
Explanation
Let’s break down the solution:
- Edge Case Handling: If ( n ) is 1 or less, return 0 since there are no proper divrs.
- Initialization: Start with a sum of 1 because it is a proper divr for all ( n >1 ).
- Loop Through Divrs: Iterate from 2 up to the integer square root of ( n ):
- For each ( i ) that divides ( n ):
- Add ( i ) to the sum.
- Compute the counterpart divr ( n//i ). If it is different from ( i ), add it to the sum (to avoid double-counting for perfect squares like 4, where ( i=2 ) and ( n//i=2 )).
- For each ( i ) that divides ( n ):
- Return Result: The total sum of proper divrs is returned.
Examples
- For ( n=6 ): Proper divrs are 1,2,3 → sum is (1+2+3=6).
- For ( n=28 ): Proper divrs are1,2,4,7,14 → sum is (1+2+4+7+14=28).
- For ( n=12 ): Proper divrs are 1,2,3,4,6 → sum is (1+2+3+4+6=16).
This approach efficiently computes the sum with a time complexity of ( O(\sqrt{n}) ), which is optimal for this problem. It handles all positive integers correctly and avoids unnecessary calculations.
Answer: The function sum_divrs(n) as defined above. For example, if you call sum_divrs(6), it returns 6; sum_divrs(28) returns28, etc. The code is ready to use.
def sum_divrs(n):
if n <= 1:
return 0
total = 1
sqrt_n = int(n ** 0.5)
for i in range(2, sqrt_n + 1):
if n % i == 0:
total += i
counterpart = n // i
if counterpart != i:
total += counterpart
return total


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。