使用PHP处理大量数字 [英] Working with large numbers in PHP

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

问题描述

要使用

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中有两个标准库可以处理任意长度/精度数字: 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处理大量数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆