Working with large numbers in PHP

前端 未结 8 839
一个人的身影
一个人的身影 2020-11-22 11:22

To use modular exponentiation as you would require when using the Fermat Primality Test with large numbers (100,000+), it calls for some very large calculations.

Whe

相关标签:
8条回答
  • 2020-11-22 11:54

    use this

     $num1 = "123456789012345678901234567890";
     $num2 = "9876543210";
     $r    = mysql_query("Select @sum:=$num1 + $num2");
     $sumR = mysql_fetch_row($r);
     $sum  = $sumR[0];
    
    0 讨论(0)
  • 2020-11-22 11:54

    I suggest you try BigInteger. If that doesn't work out, you may use SWIG to add C/C++ code for the big integer calculations and link it into your code.

    0 讨论(0)
  • 2020-11-22 11:57

    For some reason, there are two standard libraries in PHP handling the arbitrary length/precision numbers: BC Math and GMP. I personally prefer GMP, as it's fresher and has richer API.

    Based on GMP I've implemented Decimal2 class for storing and processing currency amounts (like USD 100.25). A lot of mod calculations there w/o any problems. Tested with very large numbers.

    0 讨论(0)
  • 2020-11-22 12:03
    $x = 62574 * 62574;
    
    // Cast to an integer
    $asInt = intval($x);
    var_dump($asInt);
    var_dump($asInt % 104659);
    
    // Use use sprintf to convert to integer (%d), which will casts to string
    $asIntStr = sprintf('%d', $x);
    var_dump($asIntStr);
    var_dump($asIntStr % 104659);
    
    0 讨论(0)
  • 2020-11-22 12:13

    have you taken a look at bcmod()? php has issues with integers over 2^31 - 1 on 32 bit platforms.

    var_dump(bcmod("$x", '104659') ); // string(4) "2968"
    
    0 讨论(0)
  • 2020-11-22 12:14

    I wrote a very small code for you that will surely work in case of big numbers-

    <?php
        $x = gmp_strval(gmp_mul("62574","62574")); // $x="3915505476"
        $mod=gmp_strval(gmp_mod($x,"104659"));  //$mod="2968"
    
        echo "x : ".$x."<br>";
        echo "mod : ".$mod;
    
        /* Output:
            x : 3915505476
            mod : 2968
        */
    ?>
    

    You simply have to use strings for storing big numbers and to operate on them use GMP functions in PHP.

    You may check some good GMP functions in the official PHP manual here- http://php.net/manual/en/ref.gmp.php

    0 讨论(0)
提交回复
热议问题