Understanding Schönhage-Strassen algorithm (huge i

2020-06-03 03:42发布

问题:

I need to multiply several 1000s digits long integers as efficiently as possible in Python. The numbers are read from a file.

I am trying to implement the Schönhage-Strassen algorithm for integer multiplication, but I am stuck on understanding the definition and mathematics behind it, specially the Fast Fourier Transform.

Any help to understand this algorithm, like a practical example or some pseudo-code would be highly appreciated.

回答1:

Chapter 4.3.3 of Knuth's TAOCP describes it and also has some FFT pseudocode in other chapters that could be used for this.



回答2:

1000 digits is "small" for Schönhage-Strassen to be really worth using. You may have a look at the Toom Cook multiplication. gmpy is a Python wrapper to gmp providing these functions.



回答3:

Don't reinvent the wheel. GMP has an excellent high-performance implementation of this algorithm and any algorithm written in pure Python will be at least 100 times slower, simply because Python is an interpreted language. Use gmpy to call out to GMP from your Python application. I'm also curious what application you're working on that requires multiplication of such large numbers - there might be a simpler way to handle your problem.

Also, as mentioned by other answers, "several 1000s digits long" is not nearly long enough to justify Schönhage-Strassen (you'd have to have at least 10000 decimal digits, probably more). Some variant of Toom-Cook like Toom-3 is normally used in this range. Again, don't write this yourself in Python - GMP's implementation is very carefully optimized.