PHP实现大数相加、大数相乘练习

最基本的模拟竖式的计算方法,供参考

https://github.com/hheedat/php_code/blob/master/61_multiply_two_large_numbers.php

<?php

/**
 * multiply
 * a,b should be numeric
 * @param $a string
 * @param $b string
 * @return string
 */
function mul($a, $b)
{
    $lenA = strlen($a);
    $lenB = strlen($b);

    $result = '0';
    for ($inxA = $lenA - 1; $inxA >= 0; --$inxA) {
        $re = '';
        for ($i = $inxA + 1; $i < $lenA; ++$i) {
            $re = "0" . $re;
        }
        $j = 0;
        for ($inxB = $lenB - 1; $inxB >= 0; --$inxB) {
            $mul = (int)$a[$inxA] * (int)$b[$inxB] + $j;
            if ($mul >= 10) {
                $j = floor($mul / 10);
                $mul = $mul - $j * 10;
            } else {
                $j = 0;
            }
            $re = (string)$mul . $re;
        }
        if ($j > 0) $re = (string)$j . $re;
        $result = add($result, $re);
    }

    return $result;
}

/**
 * add
 * a,b should be numeric
 * @param $a string
 * @param $b string
 * @return string
 */
function add($a, $b)
{
    $lenA = strlen($a);
    $lenB = strlen($b);

    $j = 0;
    $re = '';
    for ($inxA = $lenA - 1, $inxB = $lenB - 1; ($inxA >= 0 || $inxB >= 0); --$inxA, --$inxB) {
        $itemA = ($inxA >= 0) ? (int)$a[$inxA] : 0;
        $itemB = ($inxB >= 0) ? (int)$b[$inxB] : 0;
        $sum = $itemA + $itemB + $j;
        if ($sum > 9) {
            $j = 1;
            $sum = $sum - 10;
        } else {
            $j = 0;
        }
        $re = (string)$sum . $re;
    }
    if ($j > 0) $re = (string)$j . $re;

    return $re;
}

echo add("0", "0") . "\n";
echo add("1", "2") . "\n";
echo add("9", "8") . "\n";
echo add("1234", "4321") . "\n";
echo add("66666", "9876") . "\n";
echo add("99999999999999999999999999", "9999999999") . "\n";

echo "-------------------\n";

echo mul("0", "2") . "\n";
echo mul("0", "0") . "\n";
echo mul("1", "0") . "\n";
echo mul("1", "2") . "\n";
echo mul("123", "17") . "\n";
echo mul("9999999999", "999999") . "\n";
echo mul("999999999999999999999999999", "111111111111177999999") . "\n";

 

转载于:https://www.cnblogs.com/zyxx/p/6372295.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值