Web中长数字的操作
我想编写(不使用现有的)一个可以处理长数字(我的意思是至少几百位数字)的库(或其他东西)。
第一个问题:为其选择一种语言。 Perl/JavaScript/PHP 哪一个更好?
第二个问题:如何实现长数字的运算?我唯一得到的就是像使用数组一样使用它们,例如:
arr1 = (12, 34); //1234
arr2 = (98, 76); //9876
sum = longnumbers_add(arr1, arr2); // +
// 34 + 76 = 110 = 10 -..> 1
// 12 + 98 = 110 = 110 + 1 = 11 -..> 1
//sum == (1, 11, 10);
但它的速度很慢(至少我在 PHP 中的尝试)。也许有一些“移位位”超快速方法?
PS
我知道有 gmp 和其他很酷的库。
任何帮助表示赞赏。
I'd like to write (not to use existing one) a library (or something) that works with long numbers (I mean at least few hundred digits).
The first question: choosing a language for it. Which one is better: Perl/JavaScript/PHP?
The second question: how to implement operations with long numbers? The only thing I get is to work with them as with arrays, e.g.:
arr1 = (12, 34); //1234
arr2 = (98, 76); //9876
sum = longnumbers_add(arr1, arr2); // +
// 34 + 76 = 110 = 10 -..> 1
// 12 + 98 = 110 = 110 + 1 = 11 -..> 1
//sum == (1, 11, 10);
But it worked to slow (at least with my try in PHP). Maybe there's some "shift bits" super-fast method?
P.S.
I know there are gmp and other cool libraries.
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我为了好玩写了几个大数字库。就语言而言,我会选择您最熟悉的一种或您想了解更多的一种。对我来说,最近使用的是 JavaScript,但在我看来,这些语言都或多或少适合大数。但对于网络来说,很大一部分决定取决于您是想在客户端还是服务器端进行计算。在客户端,JavaScript 几乎是唯一的选择。
我写了几篇博客文章,展示了基本算法以及我如何选择存储它们。请注意,这些仅适用于大整数(因此没有小数点),但基础知识仍然适用。
以下是我的经验中的一些想法:
I've written a couple big number libraries for fun. As far as the language, I would either choose whichever one you're most comfortable with or one you want to learn more about. For me, that was JavaScript most recently, but in my opinion, none of those languages are any more or less suited to large numbers. For the web though, a large part of the decision comes down to whether you want to do the calculations on the client or server side. On the client side, JavaScript is pretty much the only option.
I wrote a couple blog posts demonstrating the basic algorithms and how I chose to store them. Note that these are for big integers only (so no decimal point), but the basics still apply.
Here are a few thoughts from my experience:
我不确定您是否想编写一个高级库来处理长数字(例如计算素数或其他东西),或者只是为了学习目的而实现低级运算(加法、乘法)。如果您对前者感兴趣,您应该考虑使用 Python,而不是 JavaScript/PHP/Perl。 Python 在其标准库中内置了对任意大整数的支持和用于精确浮点运算的小数类。
I'm not sure whether you want to write a high-level library for working with long numbers (e.g. for calculating primes or something) or just implement the low-level operations (addition, multiplication) for learning purposes. If you're interested in the former, you should consider Python instead of JavaScript/PHP/Perl. Python has builtin-support for arbitrarily large integers and a decimal class for exact floating point arithmetic in its standard library.
您应该尝试 BCMath:http://php.net/manual/en/book.bc。 php
You should try BCMath: http://php.net/manual/en/book.bc.php