How can I check whether a number is a power of 2? Below is what I have come up with so far:
# check every number in a vector
y <- 1:100000000
x <- 2^(0:100)
y %in% x
y[(y %in% x)==TRUE]
# check a single number
y <- 250000
x <- 2^(0:100)
y %in% x
# check a single random number
y <- sample(1000000000,1)
x <- 2^(0:100)
y %in% x
Is there a better approach? The above approach does not seem extremely general to me and it fails with very large numbers, presumably because of rounding error:
# 2^95 = 39,614,081,257,132,168,796,771,975,168
# correct
y <- 39614081257132168796771975168
x <- 2^(0:100)
y %in% x
# incorrect
y <- 39614081257132168796771975167
x <- 2^(0:100)
y %in% x
There are numerous similar questions on Stack Overflow for other languages and the answers seem to involve bit patterns. Can such an approach be used with R? Compared with that approach my approach seems unsophisticated and I am thinking there is probably a better way. Thank you for any advice.
Yes, you can look at the bit pattern in R:
isPowerOf2 <- function(x) {
n1s <- sum(as.numeric(intToBits(x)))
if (n1s == 1) {
return(TRUE)
} else {
return(FALSE)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With