How to determine if a number is power of 2?
I need to develop an algorithm in VisuAlg where I enter with a number and it tells me if it is power of 2 or not. What strategies can I use?
5 answers
For this case just apply a single Formula :
Log Value / Log 2.
If the result is a integer then the given value is based on the power of 2 .
MATHEMATICAL EXPLANATION
We have to 2 the power of x is equal to y , where y is the number you want to know if the base is equal to 2, and x is the power of 2 that will result in and .
By the properties of mathematics, and in particular that of logarithms, the solution below is presented.
Warning: Do Not round the values as shown in this example, otherwise the result will not be an integer value!!!
Thus, without rounding values , make sure that the result does not have decimal places ( integer ), and when it does not present, you will know that this value is formed by base Power 2 . Good luck!
Successively Divide your x number by 2.
If the remainder is always 0 and you get to the quotient 1 it's because x is a power of 2.
Example:
8192/2 = 4096
4096/2 = 2048
2048/2 = 1024
1024/2 = 512
512/2 = 256
256/2 = 128
128/2 = 64
64/2 = 32
32/2 = 16
16/2 = 8
8/2 = 4
4/2 = 2
2/2 = 1
8192 is a power of 2.
The most efficient way is to check if the number-1 ends in 1111...
in binary. In JavaScript this is:
function isPowOf2(v){
return v && !(v & (v - 1));
}
var test = [0, 1, 2, 4, 6, 8];
for(var i = 0; i < test.length; ++i){
console.log(test[i] + " - " + isPowOf2(test[i]));
}
Applying to 8 one can see what is happening mathematically.
v = 8 = b1000 = true
v - 1 = 8 - 1 = 7 = b0111
8 & 7 = b1000 & b0111 = 0
!(8 & 7) = !(0) = true
v && !(8 & 7) = true
Q. E. D
Divide the number by two, until the rest of the division is less than or equal to 1 (use a loop for this)
- If the remainder of the division is equal to 1 the number is power of 2
- If the rest of the division is less than 1 the number is not power of 2
"""
Ejercicio 5.7.6. Potencias de dos.
a) Escribir una función es_potencia_de_dos que reciba como parámetro un número
natural,y devuelva True si el número es una potencia de 2, y False en caso contrario.
b) Escribir una función que, dados dos números naturales pasados como parámetros, devuelva la
suma de todas las potencias de 2 que hay en el rango formado por esos números
(0sinohayningunapotenciade2entrelosdos).Utilizarlafunción es_potencia_de_dos ,
descripta en el punto anterior.
"""
import os
def clear():
""" cls de windows """
os.system('cls' if os.name == 'nt' else 'clear')
def pausar():
""" pausa de windows"""
os.system('pause')
def es_potencia_de_dos(numero):
""" Verifica si es potencia de dos, en primera instancia descartamos el 1 , que
seria 2 a la 0 luego vemos si podemos componer el numero que tenemos
como potencia de dos y de paso devolvemos que potencia de dos es , en caso de
serlo """
if numero == 1:
return True, 0
r = 1
for i in range(1, numero):
r *= 2
if r == numero:
return True, i
else:
continue
return False
def leer_numero():
return input('\nIngrese el numero que desea verificar (* para salir) ')
x = leer_numero()
while x != '*':
potencia, cual = es_potencia_de_dos(int(x))
if potencia:
print('Es potencia, 2 a la ', cual)
else:
print('No es potencia de dos')
x = leer_numero()
clear()
print('Hasta luego..')
os.system('pause')