本文介绍了在 PHP 中处理大数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Fermat Primality Test 具有大量(100,000+),它需要一些非常大的计算.

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.

当我将两个大数(例如:62574 和 62574)相乘时,PHP 似乎将结果转换为浮点数.获取它的模值会返回奇怪的值.

When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values.

$x = 62574 * 62574;
var_dump($x);          // float(3915505476) ... correct
var_dump($x % 104659); // int(-72945)  ... wtf.

有什么方法可以让 PHP 正确执行这些计算?或者,是否有另一种方法可以找到适用于大数的模数值?

Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?

推荐答案

出于某种原因,PHP 中有两个处理任意长度/精度数的标准库:BC 数学GMP.我个人更喜欢 GMP,因为它更新鲜,API 更丰富.

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.

基于 GMP,我实现了 Decimal2 类 用于存储和处理货币金额(如 100.25 美元).很多 mod 计算没有任何问题.使用非常的大量数据进行测试.

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.

这篇关于在 PHP 中处理大数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:52