★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9810573.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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)
对于一个 正整数,如果它和除了它自身以外的所有正因子之和相等,我们称它为“完美数”。
给定一个 正整数 n
, 如果他是完美数,返回 True
,否则返回 False
示例:
输入: 28 输出: True 解释: 28 = 1 + 2 + 4 + 7 + 14
注意:
输入的数字 n
不会超过 100,000,000. (1e8)
12ms
1 class Solution { 2 func checkPerfectNumber(_ num: Int) -> Bool { 3 if num < 2 4 { 5 return false 6 } 7 let n:Int = Int(sqrt(Double(num))) 8 if n < 2 9 { 10 return false 11 } 12 var ans:Int = 1 13 for i in 2...n 14 { 15 if num % i == 0 16 { 17 ans += i 18 if num / i != i 19 { 20 ans += num / i 21 } 22 } 23 } 24 return ans == num 25 } 26 }
12ms
1 class Solution { 2 func checkPerfectNumber(_ num: Int) -> Bool { 3 4 guard num > 1 else { return false } 5 6 var sum = 0 7 var i = 1 8 while Double(i) <= sqrt(Double(num)) { 9 let isDivisor = (num % i == 0) 10 if isDivisor { 11 let d1 = i 12 let d2 = num / i 13 sum = sum + d1 14 if d2 != num && d2 != d1 { 15 sum = sum + d2 16 } 17 if sum > num { return false } 18 } 19 i = i + 1 20 } 21 let isPerfect = sum == num 22 return isPerfect 23 } 24 }
16ms
1 class Solution { 2 func checkPerfectNumber(_ num: Int) -> Bool { 3 if num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336 { 4 return true 5 } 6 return false 7 } 8 }
20ms
1 class Solution { 2 func checkPerfectNumber(_ num: Int) -> Bool { 3 if num <= 1 { 4 return false 5 } 6 7 let value = sqrt(Double(num)) 8 if value.isNaN || value.isInfinite { 9 return false 10 } 11 12 let max = Int(value) 13 if max < 2 { 14 return false 15 } 16 17 var tempValue: Int = 1 18 for index in 2 ... max { 19 if num % index == 0 { 20 tempValue += index 21 tempValue += num / index 22 } 23 } 24 25 return tempValue == num 26 } 27 }
28ms
1 class Solution { 2 func f(_ num: Int) -> Bool { 3 if (num <= 1) { 4 return false 5 } 6 var a = 0 7 var max_num = Int(sqrt(Double(num))) 8 a += 1 9 if (2 <= max_num){ 10 for i in 2...max_num { 11 if num % i == 0 { 12 a += i 13 if i != num / i { 14 a += num / i 15 } 16 } 17 } 18 } 19 20 return a == num 21 } 22 23 24 func checkPerfectNumber(_ num: Int) -> Bool { 25 return f(num) 26 } 27 }