Perfect Number

https://leetcode.com/problems/perfect-number/description/

We define the Perfect Number is a positive integer that is equal to the sum of all itspositivedivisors 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.

Thoughts

依次检查从2到sqrt(num)看是否能被num整除, 能就把i和对应的num / i 加进去. 因为已经考虑过了num/ i, 所以只到sqrt(num)即可.

Code

class Solution {
    public boolean checkPerfectNumber(int num) {
        if (num <= 1) {
            return false;
        }
        int sum = 0;
        sum++;
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                sum += i + num / i;
                //System.out.println(i + ", " + num / i);
            }
        }

        return sum == num;
    }
}

Analysis

时间复杂度O(sqrt(N)).

Last updated