Golang : Check if integer is power of four example
Problem:
You need to test if a given integer is a power of 4. For example, if given number = 16, return true and if number = 9 return false.
Solution:
Test to see if the number can be divided by 4 until it is 1.
package main
import (
"fmt"
"math"
)
func isPowerOfFour(num int) bool {
for num >= 4 {
if num%4 != 0 {
return false
}
num = num / 4
}
return num == 1
}
func main() {
fmt.Println("Is 9 power of 4? : ", isPowerOfFour(9))
fmt.Println("Is 64 power of 4? : ", isPowerOfFour(64))
fmt.Println("Is 8 power of 4? : ", isPowerOfFour(8))
// if use math.Pow() function, remember to convert float64
// to int
testNumPowerOfFour := int(math.Pow(2, 4))
fmt.Println("Is 16 power of 4? : ", isPowerOfFour(testNumPowerOfFour))
testNumPowerOfFour = int(math.Pow(2, 3))
fmt.Println("Is 8 power of 4? : ", isPowerOfFour(testNumPowerOfFour))
}
Output:
Is 9 power of 4? : false
Is 64 power of 4? : true
Is 8 power of 4? : false
Is 16 power of 4? : true
Is 8 power of 4? : false
References:
https://www.socketloop.com/tutorials/golang-math-pow-the-power-of-x-y-example
See also : Golang : Math pow(the power of x^y) example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.7k Javascript : Put image into Chrome browser's console
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+11.8k Golang : Perform sanity checks on filename example
+6.8k Web : How to see your website from different countries?
+18.9k Golang : Populate dropdown with html/template example
+3.5k Java : Random alphabets, alpha-numeric or numbers only string generator
+8.8k Golang : Intercept and compare HTTP response code example
+19.1k Golang : Fix cannot download, $GOPATH not set error
+7.7k Swift : Convert (cast) String to Float
+10.9k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+6.1k Golang : Selection sort example
+7.7k Golang : Gomobile init produce "iphoneos" cannot be located error