163.Perfect Number

题目:

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

我们定义Perfect Number是一个正整数,它等于除了它自己之外的所有正除数的总和。

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

现在,给定一个整数n,编写一个函数,当它是一个完美数字时返回true,否则返回false。

 

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 class Solution {
 2     public boolean checkPerfectNumber(int num) {
 3         if(num==1) return false;
 4         int sum=1;  //1一定是sum的因子
 5         for(int i=2;i*i<=num;i++){
 6             if(num%i==0) sum+=i+num/i;  //i是num的因子,则sum/i也是sum的因子,都加上
 7             if(i*i==num) sum-=i;        //如果num是完全平方数,则i加了两次,减去一次
 8         }
 9         return sum==num;
10     }
11 }

详解:

 

posted @ 2018-09-12 20:33  chan_ai_chao  阅读(115)  评论(0编辑  收藏  举报