Home >php教程 >PHP源码 >大整数相乘法

大整数相乘法

PHP中文网
PHP中文网Original
2016-05-25 17:09:261244browse

跳至

<?php

/**
 * 大整数想乘
 */
//数字1
$n1 = "8274918237591826391827591827391827";
//数字2
$n2 = "0000000000129837293586928391837492837592837491873498216359187234986239487";

//九九乘法表
$muti = array();
for ($i = 0; $i < 10; $i++) {
    for ($j = 0; $j < 10; $j++) {
        $muti[strval($i)][strval($j)] = $i * $j;
    }
}

//最长长度
$len_1 = strlen($n1);
//最短长度
$len_2 = strlen($n2);

//结果长度
$len_r = $len_1+$len_2+1;
//运算结果
$result = array_fill(0, $len_r, 0);

//数字反序
$n1 = strrev($n1);
$n2 = strrev($n2);

//按位运算
for ($i = 0; $i < $len_1; $i++) {
    for ($j = 0; $j < $len_2; $j++) {
        $result[$i + $j] += $muti[$n1[$i]][$n2[$j]];
    }
}

//进位处理
$i = 0;
$j = $len_r-1;
do{
    $result[$i + 1] += (int) ($result[$i] / 10);
    $result[$i] = $result[$i] % 10;
}  while (++$i

                   

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn