您的位置:首页 > 其它

算法作业_11(2017.3.29第六周)

2017-03-29 19:22 239 查看
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.

class Solution {
public:
    bool checkPerfectNumber(int num) {
        if(num==1)
            return false;
        int sum =  1;
        int up =  sqrt(num);
        for(int i=2;i<=up;i++){
            if(num%i==0){
                sum = sum +i;
                sum = sum + num/i;
                
            }
        }
        return num==sum;
        
    }
};
java:
public class Solution {
public boolean checkPerfectNumber(int num) {
if(num==1){
return false;
}
int sum =1;
int up = (int)Math.sqrt(num);
for(int i =2; i<=up; i++){
if(num%i==0){
sum = sum+i;
sum = sum+num/i;

}
}
return sum == num ;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: