C#版 - Leetcode 507. 完美数 - 题解

C#版 - Leetcode 507. 完美数 - 题解

507.Perfect Number

在线提交: https://leetcode-cn.com/problems/perfect-number/

题目描述

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

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

示例:

输入: 28
输出: True
解释: 28 = 1 + 2 + 4 + 7 + 14
  • 1
  • 2
  • 3

注意:

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


  • 题目难度:Easy

  • 通过次数:492

  • 提交次数:1.9K

  • 相关话题 数学
    相似题目 自除数


思路:
方法1:
如果num有约数d,则它必有约数num/d,与判断素数时的sqrt的功能类似。因而只需存一半的值即可~

方法2:完美数有数学公式,第n个完美数为Pn=(2p1)2p1 .
Formula

相关资料:
https://simple.wikipedia.org/wiki/Perfect_number
http://www.gaimor.cn

6, 28, 496, 8128 - OEIS(用于收录整数数列规律的在线百科) 
https://oeis.org/search?q=6%2C+28%2C+496%2C+8128&sort=&language=&go=Search

Tips: 遇到整数相关的问题,考虑到OEIS网站的站内搜索功能太弱,可以使用Google site命令搜索该英文名,比如: Perfect numer site:oeis.org

已AC代码:

public class Solution
{
    public bool CheckPerfectNumber(int num)
    {
        if (num == 1)
            return false;

        List<int> divisors = new List<int>();
        for (int i = 2; i*i <= num; i++)        // store the smaller one in divisor pair, then another is num/smaller
        {
            if (num % i == 0)
                divisors.Add(i);
        }

        int sum = 1;    // 1 is divisor of any integer
        foreach (var divisor in divisors)
            sum += divisor + num/divisor;
        return num == sum;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Rank:

You are here!  Your runtime beats 92.45 % of csharp submissions.

将List换为Array,或将num%i换为num - (num/i) * i,运行速度并没提升~

public class Solution
{
    public bool CheckPerfectNumber(int num)
    {
        if (num == 1)
            return false;

        int[] divisors = {};
        for (int i = 2; i*i<=num; i++)  // Store the smaller one in divisor pair, then another is num/smaller
        {
            if (num - (num/i) * i == 0)
                divisors = divisors.Concat(new int[]
                {
                   i
                }).ToArray();
        }

        int sum = 1;   // 1 is divisor of any integer
        foreach (var divisor in divisors)
            sum += divisor + num/divisor;
        return num == sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值