Created
November 15, 2017 17:31
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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