Solution of 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.

Example:

Input: 28
Output: True

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

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

Ideas of solving a problem

When we do this problem, we should first think about how to extract the common factors.First, if a number is prime, the sum of its common factors cannot be equal to itself.If this number is 0, false is returned.If the number is not divisible by 2, such as 1,3,5,7,9,11,13,15, etc., it is found that either the number is prime or the sum of the common factors is more different from the original value.So we start at 2, and we go to its largest factor, which is num over I, and we add it in both directions, and we get the sum.The value of the sum is then compared to the original value, returning True or False. The time complexity is O(n^1/2). The space complexity is O(1). The memory consumption is 1.9 Mb.

Code

package main

import (
	"fmt"
)
func main(){
	num := 28
	fmt.Println(checkPerfectNumber(num))
}
func checkPerfectNumber(num int) bool {
	if num % 2 != 0 || num == 0 {
		return false
	}
	sum := 1
	for i:=2; i < num/i; i++ {
		if num%i == 0 {
			sum += i + num/i
		}
	}
	return sum == num
}



来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/perfect-number

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值