507. Perfect number

Title description

For a positive integer, if it is equal to the sum of all positive factors except itself, we call it a "perfect number".

Given an integer n, if it is a perfect number, return true, otherwise return false

Example

示例 1:
输入:28
输出:True
解释:28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, 和 14 是 28 的所有正因子。

示例 2:

输入:num = 6
输出:true

示例 3:

输入:num = 496
输出:true

示例 4:

输入:num = 8128
输出:true

示例 5:

输入:num = 2
输出:false

prompt

1 <= num <= 108

Problem solving ideas

The idea of ​​this question is to simply add the factors, but note that the loop variable i cannot reach num, so use i*i<=num to narrow the range

Code

bool checkPerfectNumber(int num){
    
    
    int count=0;
    if(num==1)return false;
    for(int i=2;i*i<=num;i++){
    
    
        if(num%i==0)count+=i+num/i;
    }return count+1==num?true:false;

}

Likou link

Guess you like

Origin blog.csdn.net/qq_44722674/article/details/111973279