Leetcode Note: Go - Perfect Number
Perfect Number - LeetCode
https://leetcode.com/problems/perfect-number/
- Go 言語で取り組んだメモ
所感
- int が渡されるので perfect number か判定して bool を return する
- Perfect number - Wikipedia
- 完全数 - Wikipedia
回答
Perfect Number - LeetCode
https://leetcode.com/problems/perfect-number/solution/
Golang simple iterative solution, O(logN) - LeetCode Discuss
https://leetcode.com/problems/perfect-number/discuss/112194/Golang-simple-iterative-solution-O(logN)
func checkPerfectNumber(num int) bool {
if num <= 1 {
return false
}
sum := 0
for i := 1; i*i <= num; i++ {
if num%i == 0 {
sum = sum + i + (num / i)
}
}
return sum-num == num
}
i * i <= num
を条件にループ- num を i で割り切れるなら sum を更新
sum = sum + i + (num / i)
- num を i で割り切れるなら sum を更新
sum-num == num
で bool を return