Python pow() function
The pow()
function in Python returns the result of raising a number to the power of another. It can take two or three arguments. If three arguments are provided, it computes the power and then returns the result modulo a third argument.
Syntax
x
: The base number (the number to be raised to a power).y
: The exponent (the power to which the basex
is raised).z
(optional): If provided, the result is computed as(x ** y) % z
.
Return Value
- If only two arguments are provided, it returns
x
raised to the power ofy
(i.e.,x ** y
). - If three arguments are provided, it returns
(x ** y) % z
.
Examples
Using
pow()
with two arguments:Using
pow()
with three arguments: If three arguments are provided, the result is first raised to the power and then the modulus is applied.Negative exponents: You can pass a negative exponent to calculate the inverse of the power.
Modular exponentiation (with three arguments): Modular exponentiation is efficient for large numbers because it calculates the power and applies the modulus in one step.
Using
pow()
with floats: You can also raise floating-point numbers to a power usingpow()
.
Why Use Three Arguments?
The three-argument form pow(x, y, z)
is useful for large number calculations and cryptography. It calculates the result of x ** y % z
efficiently without first computing x ** y
as a large number.
Summary
- Two arguments:
pow(x, y)
computesx
raised to the power ofy
(x ** y
). - Three arguments:
pow(x, y, z)
computes(x ** y) % z
efficiently. - Supports both positive and negative exponents, and works with integers or floating-point numbers.