PHP – bcpowmod() function

In PHP, bcpowmod() function is used to raise an arbitrary precision base number to another exponent number, reduced by a specified modulus. The bcpowmod() function accepts three arbitrary precision numbers as strings and returns the base number raised to the exponent modulo number after scaling the result to the specified precision.

Syntax

string bcpowmod(string $base, string $exponent, string $modulus, int $scale = 0)

Parameters

The bcpowmod() function accepts four different parameters − $base, $exponent, $modulus and $scale.

  • $base − It represents the base number. It is a string type parameter.

  • $exponent − It represents the exponent number. It is a string type parameter.

  • $modulus − The $modulus parameter accepts the modulus value. It is a string type parameter.

  • $scale − The $scale parameter is an integer type parameter. It states the number of digits which will come after the decimal in the result. Its default value is 0.

Return Value

The bcpowmod() function returns the result as a string. Or, it returns null if the modulus is 0 or the exponent is negative.

Example 1

The following example demonstrates basic usage of bcpowmod() without scale ?

<?php
   // input numbers with arbitrary precision
   $base = "5";
   $exponent = "7";
   $mod = "7";

   // calculates the base^exponent % mod
   $result = bcpowmod($base, $exponent, $mod);
   echo "Output without scale: ", $result;
?>
Output without scale: 5

Example 2

This example shows how the scale parameter affects the output precision ?

<?php
   // input numbers with arbitrary precision
   $base = "5";
   $exponent = "7";
   $mod = "7";

   // Scale value 4
   $scale = 4;

   // calculates the base^exponent % mod
   $result = bcpowmod($base, $exponent, $mod, $scale);
   echo "Output with scale: ", $result;
?>
Output with scale: 5.0000

Example 3

This example demonstrates working with larger numbers and decimal results ?

<?php
   $base = "123.45";
   $exponent = "3";
   $mod = "100";
   $scale = 2;

   $result = bcpowmod($base, $exponent, $mod, $scale);
   echo "Result: ", $result;
?>
Result: 74.70

Conclusion

The bcpowmod() function is essential for modular exponentiation with arbitrary precision arithmetic. It's particularly useful in cryptographic calculations and mathematical operations requiring high precision with large numbers.

Updated on: 2026-03-15T09:54:25+05:30

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements