Working with large numbers in PHP

前端 未结 8 840
一个人的身影
一个人的身影 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 12:16

    I found another solution, but the number will be stored as a string. As soon as you cast it back to a numeric, you'll be restricted to the precision of the underlying platform. On a 32 bit platform, the largest int you can represent as an int type is 2,147,483,647:

    /**
     * @param string $a
     * @param string $b
     * @return string
     */
    function terminal_add($a, $b){
        return shell_exec('echo "'.$a.'+'.$b.'"|bc');
    }
    
    // terminal_add("123456789012345678901234567890", "9876543210")
    // output: "123456789012345678911111111100"
    
    0 讨论(0)
  • 2020-11-22 12:19
    <?php
    function add($int1,$int2){
        $int1 = str_pad($int1, strlen($int2), '0', STR_PAD_LEFT);
        $int2 = str_pad($int2, strlen($int1), '0', STR_PAD_LEFT);
        $carry = 0;
        $str = "";
        for($i=strlen($int1);$i>0;$i--){
            $var = $int1[$i-1] + $int2[$i-1] + $carry;
            $var = str_pad($var, 2, '0', STR_PAD_LEFT);
            $var = (string) $var;
            $carry = $var[0];
            $str = $str . $var[1];
        }
        $res = strrev($str.$carry);
        echo ltrim($res,"0");
    }
    add($int1,$int2);
    ?>
    
    0 讨论(0)
提交回复
热议问题