[LeetCode By Go 107]507. 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)

解题思路

  1. 求出输入值num的平方根sqrt1
  2. 判断num能否将i (i属于[2, sqrt1])整除,如果可以,则将i和num/i加入num的因数和sum中
  3. 判断num和sum是否相等,如果相等,则为完美数,否则不是

注意
因子不包括自己,所以如果输入是1的话,因子不能有1,1不是完美数

代码

perfectNumber.go

package _507_Perfect_Number

import "math"

func CheckPerfectNumber(num int) bool {
    if 1 == num {
        return false
    }
    sqrt1 := int(math.Sqrt(float64(num)))
    var sum int
    sum = 1
    for i := 2; i <= sqrt1; i++ {
        if num % i == 0 {
            sum += i
            sum += num /i
        }
    }

    if sum == num {
        return true
    }

    return false
}

测试

perfectNumber_test.go

package _507_Perfect_Number

import "testing"

func TestCheckPerfectNumber(t *testing.T) {
    var tests = []struct{
        num int
        ret bool
    } {
        {6, true},
        {28, true},
        {1, false},
    }

    for _, v := range tests {
        ret := CheckPerfectNumber(v.num)

        if ret == v.ret {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %+v", v.ret, ret)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/69731980c216
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞