首页 > 其他 > 详细

163.Perfect Number

时间:2018-09-12 21:05:07      阅读:247      评论:0      收藏:0      [点我收藏+]

题目:

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 }

详解:

 

163.Perfect Number

原文:https://www.cnblogs.com/chanaichao/p/9637172.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!