LeetCode 507. Perfect Number
Created at 20171221 Updated at 20180121 Category LeetCode
Question
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
Example:


Note: The input number n will not exceed 100,000,000. (1e8)
Solution
You will get TLE(Time Limit Exceeded) if you simply loop all the values. So, to tackle this problem, there is a theorem that is: if number n is not a prime, there must be a factor d among the range of 2 and sqrt(n), the factor d is very important for noneprime numbers.
Code


Just check every i from 1 to sqrt(num). When num % i == 0, we add both i and num//i to our result. And remember to exclude the num itself and check if we added a duplicate sqrt(num) in the end.