在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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) 对于一个 正整数,如果它和除了它自身以外的所有正因子之和相等,我们称它为“完美数”。 给定一个 正整数 示例: 输入: 28 输出: True 解释: 28 = 1 + 2 + 4 + 7 + 14 注意: 输入的数字 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 }
|
请发表评论