简体   繁体   English

对非常大的数字进行算术运算的算法

[英]Algorithm for doing arithmetic operation on very large numbers

I need a algorithm to perform arithmetic operations on large numbers(that are way above range of float, double int or any other data type for that matter). 我需要一种算法来对大数执行算术运算(这超出了float,double int或任何其他数据类型的范围)。 I am required to write the code in C. I tried looking up here: Knuth, Donald, The Art of Computer Programming, ISBN 0-201-89684-2, Volume 2: Seminumerical Algorithms, Section 4.3.1: The Classical Algorithms but couldn't stand it. 我需要用C编写代码。我尝试在此处查找: Knuth,Donald,计算机编程艺术,ISBN 0-201-89684-2,第2卷:半数值算法,第4.3.1节:经典算法,但是受不了了。 I just need the algorithm not the code. 我只需要算法而不是代码。

For addition, as far as I know, you won't get much better than the simple linear O(n) algorithm, ie, just add digit by digit. 另外,据我所知,您不会比简单的线性O(n)算法好得多,也就是说,只需逐位相加即可。 You likely, have to read the entire input anyway, so it's at least linear. 您可能必须无论如何都要读取整个输入,因此至少是线性的。 You might be able to do various tricks to get the constant down. 您可能可以做各种技巧来降低常数。

Your main issue is going to be multiplication, due to the quadratic nature of the basic long multiplication algorithm. 由于基本长乘法算法的二次性质,您的主要问题将是乘法。 You might want to consider one of the several much faster methods given here . 您可能需要考虑这里给出的几种更快的方法之一。 The Karatsuba method is a little tricky to implement nicely but is probably the easiest non-trivial algorithm that will give you a gain. Karatsuba方法很难很好地实现,但它可能是最简单的非平凡算法,可以为您带来收益。 Otherwise, you'll have to look a bit more into the Fast Fourier Transform methods, such as Schönhage-Strassen's algorithm or Fürer's algorithm . 否则,您将不得不更多地研究快速傅立叶变换方法,例如Schönhage-Strassen的算法Fürer的算法

See also Big O notation . 另请参见Big O符号

I think Karatsuba algorithm is best to perform arithmetic operations on large numbers.For sufficiently large n, another generalization, the Schönhage–Strassen algorithm, is even faster. 我认为Karatsuba算法最适合对大数执行算术运算。对于足够大的n,另一种泛化算法Schönhage–Strassen算法甚至更快。 You can look for the algorithm in Karatsuba or Karatsuba_Multiplication 您可以在KaratsubaKaratsuba_Multiplication中查找算法

There is no algorithm to perform arithmetic operations on very large numbers. 没有算法可以对非常大的数字执行算术运算。 The arithmetic operations remains the same. 算术运算保持不变。 What you need is in class like http://www.codeproject.com/KB/cs/BigInt.aspx 您需要的是像http://www.codeproject.com/KB/cs/BigInt.aspx这样的类

Riesel撰写的《质数和因式分解计算机方法 》一书的附录包含了易于阅读的多精度算术代码。

For just the algorithms, read Knuth vol 2 or Crandall and Pomerance. 对于仅算法,请阅读Knuth vol 2或Crandall and Pomerance。 For the coding, I would suggest getting the obvious algorithms working first before moving on to Karatsuba or Fourier transforms. 对于编码,我建议先使用显而易见的算法,然后再进行Karatsuba或Fourier变换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM