We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
return sum([i+n/i for i in range(1, int(n**0.5)+1) if n% i ==0])
you only need to go to sqrt(n) +1.
My code above has a bug for the cases of n = m*m, such as 16=4*4. It will count m twice. Someone below posted good python code that fixed this bug, search: Solution: O(sqrt(n)):
Day 19: Interfaces
You are viewing a single comment's thread. Return to all comments →
A much faster Python solution here:
return sum([i+n/i for i in range(1, int(n**0.5)+1) if n% i ==0])
you only need to go to sqrt(n) +1.
My code above has a bug for the cases of n = m*m, such as 16=4*4. It will count m twice. Someone below posted good python code that fixed this bug, search: Solution: O(sqrt(n)):