Golang 程序检查给定数字的 4 的幂
go programmingserver side programmingprogramming
示例
例如,n = 12 => 12 不是 4 的幂。
例如,n = 64 => 64 是 4 的幂。
解决此问题的方法
步骤 1 − 定义一个接受数字 n 的方法。
步骤 2 − 将 log(n) 除以 log(4),存储在 res 中。
步骤 3 −如果 res 的 floor 与 res 相同,则打印 n 是 4 的幂。
步骤 4 − 否则,打印 n 不是 4 的幂。
示例
package main import ( "fmt" "math" ) func CheckPowerOf4(n int){ res := math.Log(float64(n)) / math.Log(float64(4)) if res == math.Floor(res) { fmt.Printf("%d is the power of 4.\n", n) } else { fmt.Printf("%d is not the power of 4.\n", n) } } func main(){ CheckPowerOf4(13) CheckPowerOf4(16) CheckPowerOf4(0) }
输出
13 is not the power of 4. 16 is the power of 4. 0 is the power of 4.