Last active
January 7, 2017 17:18
-
-
Save jamesmcnamara/e91f1f4d14a136b1753604704a3af42b to your computer and use it in GitHub Desktop.
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, floor, ceil | |
is_odd = lambda n: n % 2 | |
is_even = lambda n: not is_odd(n) | |
log2 = lambda n: log(n, 2) | |
is_power_of_2 = lambda n: log2(n) == int(log2(n)) | |
def find_number_of_steps(n): | |
if is_power_of_2(n): | |
return log2(n) | |
if is_even(n): | |
return min(steps_from_closest_power_of_2(n), 1 + find_number_of_steps(n / 2)) | |
if is_odd(n): | |
return 1 + min(find_number_of_steps(n + 1), find_number_of_steps(n - 1)) | |
def steps_from_closest_power_of_2(n): | |
m = log2(n) | |
m_up = ceil(m) | |
m_down = floor(m) | |
return min(abs(n - m_up) + m_up, abs(n - m_down) + m_down) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment