php 超大整数乘法的简单示例

前端之家收集整理的这篇文章主要介绍了php 超大整数乘法的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP实现超大整数乘法感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

/**
 * PHP实现超大整数乘法
 *
 * @param 
 * @arrange 网: www.jb51.cc
*/
//数字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<$j);
//var_dump($result);
//exit();
$i = $j - 1;
//去除前导0
while ($i && !$result[$i--]) {
};
//输出结果
$i++;
do {
	echo $result[$i];
} while ($i--);

/***   来自编程之家 jb51.cc(jb51.cc)   ***/
原文链接:https://www.f2er.com/php/528618.html

猜你在找的PHP相关文章