Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast multiplication of very large integers

How to multiply two very large numbers greater than 32 characters for example multiplication of 100! with 122! or 22^122 with 11^200 by the help of divide and conquer, do any body have java code or C# code?

like image 577
khan Avatar asked Jan 03 '10 22:01

khan


People also ask

How do you multiply large integers?

Multiplying large numbers together is performed by multiplying the ones digit of the bottom number to the entire top number. After the ones place value has finished multiplying, move to the tens place value in the bottom number and multiply that digit by the top number.

What is the fastest integer multiplication algorithm?

For more than 35 years, the fastest known method for integer multiplication has been the Schönhage-Strassen algorithm running in time O(nlog nlog log n). Under certain restrictive conditions there is a corresponding Ω(nlog n) lower bound.


2 Answers

You should probably use java.math.BigInteger. This allows representations of integer values well in excess of 2^32 or even 2^64. BigInteger values are essentially limited only by the amount of memory available to the program, i.e. ~4 GB on a 32-bit system and pretty much available physical+virutal memory for 64-bit systems.

import java.math.BigInteger;

class Foo
{
    public static void main(String args[])
    {
        BigInteger bigInteger100Fact = bigFactorial(BigInteger("100")); //where bigFactorial is a user-defined function to calculate a factorial
        BigInteger bigIntegerBar = new BigInteger("12390347425734985347537986930458903458");

        BigInteger product = bigIntegerFact.multiply(bigIntegerBar);
    }
}

EDIT: Here's a BigInteger factorial function if you need one

like image 125
Chinmay Kanchi Avatar answered Oct 04 '22 04:10

Chinmay Kanchi


Here is a patched version of java.lang.BigInteger that uses Karatsuba and Toom-Cook:

And here is a Java class that can multiply BigIntegers using Schönhage-Strassen:

like image 26
Tim Buktu Avatar answered Oct 04 '22 04:10

Tim Buktu