Hướng dẫn dùng exponential modulo trong PHP

Versions of PHP prior to 5 do not have bcpowmod in their repertoire.  This routine simulates this function using bcdiv, bcmod and bcmul.  It is useful to have bcpowmod available because it is commonly used to implement the RSA algorithm.

The function bcpowmod[v, e, m] is supposedly equivalent to bcmod[bcpow[v, e], m].  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1.

This routine will iterate through a loop squaring the result, modulo the modulus, for every one-bit in the exponent.  The exponent is shifted right by one bit for each iteration.  When it has been reduced to zero, the calculation ends.

This method may be slower than bcpowmod but at least it works.

function PowModSim[$Value, $Exponent, $Modulus]
  {
  // Check if simulation is even necessary.
  if [function_exists["bcpowmod"]]
    return [bcpowmod[$Value, $Exponent, $Modulus]];

  // Loop until the exponent is reduced to zero.
  $Result = "1";

  while [TRUE]
    {
    if [bcmod[$Exponent, 2] == "1"]
      $Result = bcmod[bcmul[$Result, $Value], $Modulus];

    if [[$Exponent = bcdiv[$Exponent, 2]] == "0"] break;

    $Value = bcmod[bcmul[$Value, $Value], $Modulus];
    }

  return [$Result];
  }

In the gettype[] manual, it says "[for historical reasons "double" is returned in case of a float, and not simply "float"] ".

However, I think that internally PHP sometimes uses the C double definition [i.e. a double is twice the size of a float/real]. See the example below:

//Function required to reverse a string on blocks of two
function strrev_x[$s, $x = 2] {
    if [$x
[The strrev_x-bin2hex combination is just to give printable characters.]

Given that PHP treats doubles and floats identically, I'd expected the same string as output, however, the output is:

double pack
string[16] "3ff999999999999a" //Here you see that there is a minute difference...
string[16] "3ff9999999999998"
float pack
string[8] "3fcccccd" //... which doesn't exist here
string[8] "3fcccccd"

So, as an alternative to using
  $float1 === $float2
one could use
  pack['f', $float1] === pack ['f', $float2]
with a big footnote that one should really remember that one is *reducing* your accuracy of the comparison. AFAIK is this the only way [apart from epsilon methods] to securely compare two floats.

Chủ Đề