Last active
June 7, 2016 16:20
-
-
Save clarle/43813766c7dd4bf1f8988656ca1ad512 to your computer and use it in GitHub Desktop.
Closest Mersenne function - optimized for readability, not performance
This file contains 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
from math import log | |
def round_base_2(n): | |
return 2**round(log(n)/log(2)) | |
def closest_mersenne(n): | |
rb2 = round_base_2(n) | |
# We got the closest power of 2, so you can just drop the first digit and replace all others with 1 | |
result = bin(rb2)[3:].replace('0', '1') | |
return int(result, 2) | |
n = 16777214 | |
print("The closest Mersenne to {} is {}.".format(n, closest_mersenne(n))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment