507. Perfect Number

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:

Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

 Note: The input number n will not exceed 100,000,000. (1e8)

题目含义:判断一个整数是否能由它的多个因子累加而成?

 1     public boolean checkPerfectNumber(int num) {
 2 //        于1肯定是因子,可以提前加上,那么我们找其他因子的范围是[2, sqrt(n)]。我们遍历这之间所有的数字,如果可以被n整除,
 3 //        那么我们把i和num/i都加上,对于n如果是平方数的话,那么我们此时相同的因子加来两次,所以我们要减掉一次。
 4 //        还有就是在遍历的过程中如果累积和sum大于n了,直接返回false即可。在循环结束后,我们看sum是否和num相等
 5         if (num==1) return false;
 6         int sum=1;
 7         for (int i=2;i<Math.sqrt(num);i++)
 8         {
 9             if(num%i==0) sum += i + num/i; //找到两个因子,加到累积和sum中
10             if(num == i*i) sum -=i; //相同的因子,只加一次
11             if (sum > num) return false;
12         }
13         return sum == num;       
14     }
原文地址:https://www.cnblogs.com/wzj4858/p/7701611.html