# C#LeetCode刷题之#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.

Input: 28

Output: True

Explanation: 28 = 1 + 2 + 4 + 7 + 14

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

```public class Program {

public static void Main(string[] args) {
var num = 6;
var res = CheckPerfectNumber(num);
Console.WriteLine(res);

num = 496;
res = CheckPerfectNumber2(num);
Console.WriteLine(res);

}

private static bool CheckPerfectNumber(int num) {
//28 = 1 + 2 + 4 + 7 + 14
//以根号 28 = 5.29 为分水岭
//若 2 能被 28 整除，28 / 2 = 14
//则 2 和 14 都需要计入计算和的范围之内
//边界处理
if(num == 1) return false;
//1 总是因子，提前 + 1
var sum = 1;
//从 2 到 Math.Sqrt(num)
for(var i = 2; i <= Math.Sqrt(num); i++) {
//若整除，则被除数和商均计入累计和
if(num % i == 0) {
sum += i + num / i;
}
}
//满足完美数定义时返回true，否则返回false
return sum == num;
}

private static bool CheckPerfectNumber2(int num) {
//题目范围内只包含这 5 个完美数
//套用强哥的一句话，我从未见过如此厚颜无耻之人
return num == 6 || num == 28 ||
num == 496 || num == 8128 ||
num == 33550336;
}

}```

```True
True```

(1)