the summation of all proper divisors of a number

Question:

Problem is from online judge site. I have no idea how my code fails in the tests. I tried possible edge cases but https://www.spoj.com/problems/DIVSUM/, website still gave me error, At first try i went on brute force and loop throught 1 to input number, but efficiency was poor then i search how to develop better solution and found a really good solution to decrase complexity to sqrt(n).
Given a natural number n (1 <= n <= 500000), please output the summation of all its proper divisors.

Definition: A proper divisor of a natural number is the divisor that is strictly less than the number.

e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.

import math


def divisorSummation(inp):
    divisorsSum = 0
    if(inp == 1):
        return 0

    for i in range(1,  int(math.sqrt((inp)))+1):
        if(inp % i == 0):
            divisorsSum += i
            if(i*i != inp and i != 1):
                divisorsSum += inp / i

    return(int(divisorsSum))

value = int(input())
for i in range(value):
    (divisorSummation(int(input())))
Asked By: Mocak

||

Answers:

Your code works fine. In fact, I submitted your code (with modifications to include output) and it was accepted. Check https://www.spoj.com/status/ ID 30064357 for proof.

import math

def divisorSummation(inp):
    if inp == 1:
        return 0
    
    divisorsSum = 0
    for i in range(1, int(math.sqrt(inp)) + 1):
        if inp % i == 0:
            divisorsSum += i
            if i * i != inp and i != 1:
                divisorsSum += inp // i

    return divisorsSum    

for _ in range(int(input())):
    print(divisorSummation(int(input())))
Answered By: JRose
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.