Binary Exponentiation Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Binary Exponentiation runs in O(log n) time and O(1) space, in Python as in every other language.
- ✓The three-argument builtin pow(base, exp, mod) IS binary exponentiation -- CPython implements it in C on the arbitrary-precision int type, walking the bits of exp and squaring/reducing at every step.
- ✓Reach for the builtin pow(base, exp, mod) rather than hand-rolling a while loop -- it is implemented in C, handles negative and zero exponents, and is the form every reviewer expects for modular exponentiation.
- ✓The Python trap: Calling the two-argument pow(base, exp) (or base ** exp) on a large exponent with no modulus builds the FULL result as an arbitrary-precision int before you ever get to reduce it -- a ** 1_000_000 % m allocates and multiplies a number with hundreds of thousands of digits just to throw most of it away.
- ✓pow(base, exp, mod) does about log2(exp) squarings plus up to that many multiplications, matching the public O(log n) bound, and because the modulus keeps every intermediate value bounded to the modulus's digit count, each multiplication stays cheap and roughly constant-width throughout.
What Binary Exponentiation actually is
Binary Exponentiation in Python: what you actually reach for
Python implementation
def bin_pow(base: int, exp: int, mod: int | None = None) -> int:
"""Reference loop -- real code should use the 3-arg builtin below instead."""
result = 1
base = base % mod if mod else base
while exp > 0:
if exp & 1:
result = result * base % mod if mod else result * base
base = base * base % mod if mod else base * base
exp >>= 1
return result
# what you actually write: CPython's C-level binary exponentiation
modexp = pow(3, 200, 1_000_000_007) # a**n mod m, O(log n) squarings in C
inverse = pow(3, -1, 1_000_000_007) # modular inverse, added in Python 3.8Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Binary Exponentiation?
The three-argument builtin pow(base, exp, mod) IS binary exponentiation -- CPython implements it in C on the arbitrary-precision int type, walking the bits of exp and squaring/reducing at every step. Two-argument pow(base, exp) or base ** exp does the same squaring walk without a modulus. Since 3.8, pow(base, -1, mod) computes the modular multiplicative inverse via the extended Euclidean algorithm, through the same C entry point.
What is the most common Python mistake when implementing Binary Exponentiation?
Calling the two-argument pow(base, exp) (or base ** exp) on a large exponent with no modulus builds the FULL result as an arbitrary-precision int before you ever get to reduce it -- a ** 1_000_000 % m allocates and multiplies a number with hundreds of thousands of digits just to throw most of it away. The fix is always to pass the modulus as pow's third argument so the reduction happens after every squaring instead of once at the very end.
How does Binary Exponentiation actually perform in Python?
pow(base, exp, mod) does about log2(exp) squarings plus up to that many multiplications, matching the public O(log n) bound, and because the modulus keeps every intermediate value bounded to the modulus's digit count, each multiplication stays cheap and roughly constant-width throughout. Drop the modulus and the intermediate a ** k grows on every squaring, so each multiplication itself gets more expensive as the operand widens (CPython switches from schoolbook to Karatsuba multiplication past its KARATSUBA_CUTOFF, 70 internal digits), making the unmodded path far more than O(log n) machine instructions even though it is still O(log n) multiplications. Time complexity is O(log n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.