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