Skip to content

Instantly share code, notes, and snippets.

@tyler-cromwell
Created November 15, 2017 17:31
Show Gist options
  • Select an option

  • Save tyler-cromwell/cafb2f9b97902fc81d67074010fc8655 to your computer and use it in GitHub Desktop.

Select an option

Save tyler-cromwell/cafb2f9b97902fc81d67074010fc8655 to your computer and use it in GitHub Desktop.
Test if a number is a power of a certain number (default: 2)
#!/usr/bin/env python3
import math
def is_power_of(n, b):
# Outside domain of logarithm
if n <= 0:
return False
# Determine power x to raise b to, to get n
x = math.log(n, b)
# If result is a whole number
if x == math.floor(x):
return True
else:
return False
if __name__ == '__main__':
# Examples
b = 2
for i in range(10):
print('Is', i, 'a power of', b, ':', is_power_of(i, b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment