The pow()
function calculates the power of a number (base ** exponent
) efficiently. It also supports an optional modulo operation, making it useful for cryptography, mathematical calculations, and performance optimizations.
Example
print(pow(2, 3))
# Output: 8 (2³ = 8)
This raises 2
to the power of 3
.
Syntax
pow(base, exponent, mod=None)
- base → The number to raise.
- exponent → The power to raise it to.
- mod (optional) → A number for modulo operation (
(base ** exponent) % mod
). - Returns → The result of the exponentiation, optionally modded.
1. Calculating Power
print(pow(5, 3))
# Output: 125 (5³ = 125)
Same as 5 ** 3
.
2. Using pow()
with Modulo
print(pow(5, 3, 7))
# Output: 6 (5³ % 7 = 125 % 7 = 6)
This computes efficiently for large numbers.
3. Using pow()
with Negative Exponents
print(pow(2, -3))
# Output: 0.125 (2⁻³ = 1/8)
Same as 1 / (2 ** 3)
.
4. Faster Modulo for Cryptography
print(pow(3, 200, 13))
# Output: 9 (Huge exponent handled efficiently)
Useful in RSA encryption and modular arithmetic.
5. Comparing pow()
with **
Operator
print(2 ** 10) # Output: 1024
print(pow(2, 10)) # Output: 1024
Both give the same result, but pow()
is faster for modulo calculations.
Key Notes
- ✔ Calculates exponents (
base ** exponent
) efficiently. - ✔ Supports modulo operation for optimized performance.
- ✔ Works with negative exponents.
- ✔ Great for cryptography and large numbers.
By using pow()
, you can perform fast exponentiation, optimize calculations, and work with modular arithmetic. 🚀