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.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP