Skip to content

Instantly share code, notes, and snippets.

@phoenixperry
Last active January 3, 2016 21:47
Show Gist options
  • Save phoenixperry/97356684a2430471ae20 to your computer and use it in GitHub Desktop.
Save phoenixperry/97356684a2430471ae20 to your computer and use it in GitHub Desktop.
#the goal of this app is to get the user to put in a power of two under 512 and then count up in powers of two until you
#get to 512, outputting the results along the way.
import math
def powersOfTwo(x):
isAPowerOfTwo = not(x == 0) and not(x & (x - 1)); #test to see if you have a power of two
#the way this works is
#step 1 make sure we've not got 0
#step 2 and make sure that you've got a legit power of 2. This is a bitwise AND operator
# Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows
#a = 0011 1100
#b = 0000 1101
#-----------------
#a&b = 0000 1100
#it compares which bits are the same and gives us a new number based on just the matching bits
#think it through let's take the number 9
#00001001 (9)
#00001000 (if we subtract 1 we get 8)
#----------
#00001000 if we take their bitwise 'AND' value we get 8
#this returns a false from our not(8) operation. Why? only not(0) evaluates to true. 0 = false in computing so if you flip false you get true. this expression only is true when you do not have 0 and you do not return a value that's larger than 0. why?
#00001000 & (8 a power of tw0)
#00000111 (minus 1 is 7)
#----------
#00000000 we get 0! Magics! So much magics! it's because any power of two will turn on all the switches behind it to equal the largest possible value
#WITCHCRAFT! Unholy bit magic!
#Does this & operation look familiar? It should- it's an and gate from hardware!! HOLY SHIT MIND BLOW! Guess what? An ~ binary ones compoent operator is a NAND gate. Yep - it's all the same. :D
if(isAPowerOfTwo ==True and x <= 512): #test to make sure it's under 512 if it's a power of two
print("you entered " + str(x)) #tell the user were we're starting our count from
while(x < 512):
x = x << 1 #bitshift x to the left until we hit 512 :D Same thing as in the much longer to read form of the code
print(x) #print ouot the value
elif (isAPowerOfTwo): #else tell the user it's over 512 and a power of two
print(str(x) + " isn't under 512")
else: #else tell the user it's not a power of two at all
print(str(x) + " is not a power of Two")
#######################
#this is the main loop for the application
ran = False
while(ran == False):
try:
num = raw_input ("Enter a power of Two up to 512: ")
num = int(num)
powersOfTwo(num)
ran = True
except ValueError:
print "Oops! That was no valid number. Try again..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment