Binary Exponentiation
You might have already seen that, with 1 → 2 → 4 → 8 → 16 as our chain, 16 + 4 will give us 20. But how would we do this in a way that a computer can do when we have hundreds of numbers in our chain?
Well, representing a number as a sum of powers of two is the very definition of binary:
We just add up all of the powers of two that correspond to ones in binary. The number of ones, called the Hamming weight, will determine how efficient this becomes. Numbers right below a power of 2, like , require the most additions: powers of two require the fewest relative to their size.
The algorithm ends up as follows. To find :
- Compute , up until the last power of 2 before , computing each new term by squaring the previous term.. Store these powers in a list, call it
l
. - Set a working variable
product = 1
- For each bit of n: if it's a one, set
product = product * l[i]
where2^i
is the place of the bit. - Return
product
Binary Exponentiation
You might have already seen that, with 1 → 2 → 4 → 8 → 16 as our chain, 16 + 4 will give us 20. But how would we do this in a way that a computer can do when we have hundreds of numbers in our chain?
Well, representing a number as a sum of powers of two is the very definition of binary:
We just add up all of the powers of two that correspond to ones in binary. The number of ones, called the Hamming weight, will determine how efficient this becomes. Numbers right below a power of 2, like , require the most additions: powers of two require the fewest relative to their size.
The algorithm ends up as follows. To find :
- Compute , up until the last power of 2 before , computing each new term by squaring the previous term.. Store these powers in a list, call it
l
. - Set a working variable
product = 1
- For each bit of n: if it's a one, set
product = product * l[i]
where2^i
is the place of the bit. - Return
product