C#LeetCode刷题之#507-完美数(Perfect Number)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82952605

问题

对于一个 正整数,如果它和除了它自身以外的所有正因子之和相等,我们称它为“完美数”。

给定一个 正整数 n, 如果他是完美数,返回 True,否则返回 False

输入: 28

输出: True

解释: 28 = 1 + 2 + 4 + 7 + 14

注意:输入的数字 n 不会超过 100,000,000. (1e8)


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);

        Console.ReadKey();
    }

    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;
    }

}

以上给出2种算法实现,以下是这个案例的输出结果:

True
True

分析:

显而易见,CheckPerfectNumber 的时间复杂度为: O(n) ,CheckPerfectNumber2 的时间复杂度为: O(1) 。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82952605