Golang 程式,用於檢查給定數字的 4 次冪


示例

例如,n = 12 => 12 不是 4 的冪。

例如,n = 64 => 64 是 4 的冪。

解決此問題的步驟

步驟 1 − 定義一個接受數字 n 的方法。

步驟 2 − 將 log(n) 除以 log(4),儲存到 res 中。

步驟 3 − 如果 res 的向下取整與 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.

更新於:2021 年 3 月 18 日

174 次瀏覽

開啟您的職業生涯

獲得認證

開始
廣告
© . All rights reserved.