Skip to content

Instantly share code, notes, and snippets.

@clarle
Last active June 7, 2016 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarle/43813766c7dd4bf1f8988656ca1ad512 to your computer and use it in GitHub Desktop.
Save clarle/43813766c7dd4bf1f8988656ca1ad512 to your computer and use it in GitHub Desktop.
Closest Mersenne function - optimized for readability, not performance
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