Last active
January 6, 2019 07:49
-
-
Save rameshrvr/0b12dfbae69ba7a8f5be01dfd5fcf029 to your computer and use it in GitHub Desktop.
Calculate 2^N where N upto 10^20 in O(1) complexity. (Fastest way to compute large power of 2 modulo a number)
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
MODULO = 1000000007 | |
def calc_power_of_two(number): | |
# i have taken 60 as base number for 64 bit processor | |
if number <= 60: | |
# Fastest way to calculate 2^N is to left shift binary 1 to N times | |
return (1 << number) | |
quotient = int(number / 60) % MODULO | |
reminder = number % 60 | |
two_power_sixty = 1 << 60 | |
# We can represent 2^N as 2^((quotient * 60) + reminder) | |
# RESULT = quotient * (2^60) * (2^reminder) | |
return ((quotient * two_power_sixty) % MODULO * (1 << reminder)) % MODULO | |
if __name__ == '__main__': | |
number = int(input("Enter any number: ")) | |
print(calc_power_of_two(number=number)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment