什么基数更适合我的 BigInteger 库?

发布于 2024-12-01 10:46:06 字数 150 浏览 0 评论 0原文

我用 C++ 开发了自己的 BigInteger 库,出于教学目的,最初我使用基数 10,它对于加、减和乘法工作得很好,但对于某些算法,如求幂、模幂和除法,它似乎更合适使用基础 2.

我正在考虑从头开始重新启动我的项目,我想知道您认为哪个基础更合适,为什么?。提前致谢!

I have developed my own BigInteger library in C++, for didactic purpose, initially I have used base 10 and it works fine for add, subtract and multiply, but for some algorithms such as exponentiation, modular exponentiation and division it appears to be more appropriate use base 2.

I am thinking restart my project from scratch and I would know what base do you think is more adequate and why?. Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

许仙没带伞 2024-12-08 10:46:06

如果您查看大多数 BigNum 类型库,您会发现它们是构建在现有的“SmallNum”数据类型之上的。这些“SmallNum”数据类型(short、int、long、float、double...)由于多种原因而采用二进制形式。如果使用(例如)unsigned int 向量,您的代码将比基数 10 位数字的向量快得多(快得多、快得多!)。

这是性能确实很重要的地方之一。假设您使用 BigNum 包来解决无需求助于 BigNum 即可解决的问题。即使是最好的 BigNum 库也会比简单的非 BigNum 方法慢得多(非常非常慢)。如果您尝试解决超出标准表示范围的问题,那么性能损失将使事情变得更糟。

克服这种固有缺陷的最佳方法是尽可能多地利用内置类型。

If you look at most BigNum type libraries you will see that they are built on top of the existing "SmallNum" data types. These "SmallNum" data types (short, int, long, float, double, ...) are in binary for too many reasons to count. Rather than a vector of base 10 digits, your code will be much faster (much, much, much faster!) if work with a vector of (for example) unsigned ints.

This is one of those places where performance does count. Suppose you use a BigNum package to solve a problem that could be solved without resorting to BigNums. Even the best BigNum library will be much slower (much, much slower) than will a simplistic, non-BigNum approach. If you try to solve a problem that is beyond the bounds of the standard representations that performance penalty will make things even worse.

The best way to overcome this inherent penalty is to take as much advantage of the builtin types as you possibly can.

烧了回忆取暖 2024-12-08 10:46:06

与目标机器上的字大小相同的基数,其中字 x 字 = 双字作为原语。原始操作按照机器指令巧妙地进行。

A base the same as the word size on your target machine, where you have word x word = doubleword as a primitive. The primitive operations work out neatly in terms of machine instructions.

栖竹 2024-12-08 10:46:06

以 10 为基数的表示对于 BigDecimal 类型有意义,您需要在其中精确地表示小数分数(用于金融计算等)。

我看不出使用以 10 为基数的 BigInteger 表示有多大好处。它使字符串转换变得非常容易,但代价是使数学运算变得更加复杂。在大多数情况下,这似乎不是一个好的权衡。

A base 10 representation makes sense for a BigDecimal type, where you need to need to represent decimal fractions exactly (for financial calculations and the like).

I can't see much benefit to using a base 10 representation for a BigInteger. It makes string conversion really easy, but at the expense of making mathematical operations much more complicated. This doesn't seem like a good tradeoff in most cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文