mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-06-18 11:59:33 -04:00
Create binary_exponentiation.py
This commit is contained in:
parent
48d1683be5
commit
65615f2f05
1 changed files with 22 additions and 0 deletions
22
math/binary_exponentiation.py
Normal file
22
math/binary_exponentiation.py
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# author: bt3gl
|
||||||
|
|
||||||
|
```
|
||||||
|
Binary exponentiation, also known as exponentiation by squaring, is a technique for
|
||||||
|
efficiently computing the power of a number. By repeatedly squaring x and halving n,
|
||||||
|
we can quickly compute x^n using a logarithmic number of multiplications.
|
||||||
|
````
|
||||||
|
|
||||||
|
def binary_exp(x: float, n: int) -> float:
|
||||||
|
|
||||||
|
if n == 0:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if n < 0:
|
||||||
|
return 1.0 / binary_exp(x, -1 * n)
|
||||||
|
|
||||||
|
if n % 2 == 1:
|
||||||
|
return x * binary_exp(x * x, (n - 1) // 2)
|
||||||
|
|
||||||
|
return binary_exp(x * x, n // 2)
|
Loading…
Add table
Add a link
Reference in a new issue