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

pow(x, y[, z])
  • x: The base number (the number to be raised to a power).
  • y: The exponent (the power to which the base x 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 of y (i.e., x ** y).
  • If three arguments are provided, it returns (x ** y) % z.

Examples

  1. Using pow() with two arguments:

    print(pow(2, 3)) # Output: 8 (2 raised to the power of 3) print(pow(5, 2)) # Output: 25 (5 squared)
  2. Using pow() with three arguments: If three arguments are provided, the result is first raised to the power and then the modulus is applied.

    print(pow(2, 3, 5)) # Output: 3 ((2 ** 3) % 5 = 8 % 5 = 3)
  3. Negative exponents: You can pass a negative exponent to calculate the inverse of the power.

    print(pow(2, -2)) # Output: 0.25 (2 raised to the power of -2, which is 1/4)
  4. Modular exponentiation (with three arguments): Modular exponentiation is efficient for large numbers because it calculates the power and applies the modulus in one step.

    print(pow(3, 4, 7)) # Output: 4 ((3 ** 4) % 7 = 81 % 7 = 4)
  5. Using pow() with floats: You can also raise floating-point numbers to a power using pow().

    print(pow(2.5, 3)) # Output: 15.625

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) computes x raised to the power of y (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.