The Wayback Machine - https://web.archive.org/web/20241119031604/https://www.geeksforgeeks.org/java-program-to-implement-the-schonhage-strassen-algorithm-for-multiplication-of-two-numbers/
Open In App

Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers

Last Updated : 12 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Schonhage-Strassen algorithm is one of the fastest ways of multiplying very large integer values (30000 to 150000 decimal digits). This algorithm was developed by Arnold Schönhage and Volker Strassen. Though the Furer’s algorithm is faster than that of Schonhage-Strassen’s algorithm, there are no practical applications for it, except Galactic algorithms (probably not used for any data present on the earth). So, Schonhage-Strassen’s algorithm is considered the best for multiplying large integer values.

In this approach of multiplication, the two integers are first multiplied without performing carry. The result set then obtained is called Acyclic Convolution or Linear Convolution. Then we perform carry on the individual columns of the Linear Convolution.

Examples: 

Java




// Java program to implement Schonhage-Strassen's
// Multiplication Algorithm
import java.io.*;
 
class GFG {
    // two class level variables to
    // store the given values
    static long a, b;
    // class level array to store the LinearConvolution
    static int[] linearConvolution;
    // an integer variable to determine
    // the length of the LinearConvolution
    static int length;
 
    // to count the no.of digits in each of
    // the given values a and b
    static int countDigits(long num)
    {
        // an integer variable initialized to
        // 0 to store the no.of digits
        int count = 0;
        // as long as the number is
        // greater than 0, divide it by 10
        // and increment the count
        while (num > 0) {
            num /= 10;
            count++;
        }
        // return the count when number becomes 0
        return count;
    }
 
    // to perform schonhage-Strassen's Multiplication
    static void schonhageStrassenMultiplication()
    {
        // first find the LinearConvolution
        findLinearConvolution();
        // Then perform carry on it
        performCarry();
    }
 
    // to find LinearConvolution
    static void findLinearConvolution()
    {
        // no.of digits in first number (a)
        int aDigits = countDigits(a);
        // no.of digits in second number (b)
        int bDigits = countDigits(b);
        // a temporary variable to store the value of a
        long temp = a;
        // length of the LinearConvolution is
        // 1 less than the no.of Digits in a +
        // no.of digits in b
        length = aDigits + bDigits - 1;
        linearConvolution = new int[length];
        for (int i = 0; i < aDigits; i++, b /= 10) {
            a = temp;
            for (int j = 0; j < bDigits; j++, a /= 10) {
                // multiply the current digit of a with
                // current digit of b and store in
                // LinearConvolution
                linearConvolution[i + j]
                    += (b % 10) * (a % 10);
            }
        }
        System.out.print("The Linear Convolution is: [ ");
        for (int i = length - 1; i >= 0; i--) {
            // print the LinearConvolution array
            System.out.print(linearConvolution[i] + "  ");
        }
        System.out.println("]");
    }
 
    // to perform carry on the obtained LinearConvolution
    static void performCarry()
    {
        // initialize product to 0
        long product = 0;
        int carry = 0, base = 1;
        // for every value in the LinearConvolution
        for (int i = 0; i < length; i++) {
            linearConvolution[i] += carry;
            // add the product of base and units digit of
            // LinearConvolution[i] to the product
            product
                = product
                  + (base * (linearConvolution[i] % 10));
            // now LinearConvolution[i]/10
            // will become the carry
            carry = linearConvolution[i] / 10;
            base *= 10;
        }
        System.out.println("\nThe Product is : " + product);
    }
 
    // Driver method
    public static void main(String[] args)
    {
        // initialize the two declared class variables with
        // the desired values
        a = 2604;
        b = 1812;
        // call schonhageStrassenMultiplication() method
        schonhageStrassenMultiplication();
    }
}


 
 

Output

The Linear Convolution is: [ 2  22  50  14  44  4  8  ]

The Product is : 4718448

 

Time Complexity: O(nlogn)

Auxiliary Space: O(n) because it is using extra space for array linearConvolution

 



Similar Reads

Implementing Strassen’s Algorithm in Java
Strassen's algorithm is used for the multiplication of Square Matrices that is the order of matrices should be (N x N). Strassen's Algorithm is based on the divide and conquer technique. In simpler terms, it is used for matrix multiplication. Strassen's method of matrix multiplication is a typical divide and conquer algorithm. However, let’s get ag
8 min read
Java Program to Implement the Karatsuba Multiplication Algorithm
It is a replacement for the algorithm that we have used since childhood, which is mainly for multiplying numbers of bigger digits. The Karatsuba Algorithm is used for the fast multiplication of large numbers, using a famous technique called as the Divide and Conquer ,developed by Anatolii Alexeevitch Karatsuba in 1960. Before entering into the topi
4 min read
Java Program to Implement Park-Miller Random Number Generation Algorithm
Park–Miller random number generator is also known as Lehmer random number generator. A general formula of a random number generator (RNG) of this type is, Xk+1 = a * xk mod m Where the modulus m is a prime number or a power of a prime number, the multiplier a is an element of high multiplicative order modulo m, and the seed X0 is coprime to m. Algo
3 min read
Java Program to Implement Bitap Algorithm for String Matching
The Bitap Algorithm is an approximate string matching algorithm. The algorithm tells whether a given text contains a substring which is "approximately equal" to a given pattern. Here approximately equal states that if the substring and pattern are within a given distance k of each other. The algorithm begins by precomputing a set of bitmasks contai
5 min read
Java Program to Implement Pollard Rho Algorithm
Pollard's rho algorithm is an algorithm for integer factorization. It is particularly effective at splitting composite numbers with small factors. The Rho algorithm’s most remarkable success was the factorization of eighth Fermat number: 1238926361552897 * 93461639715357977769163558199606896584051237541638188580280321. This algorithm was a good cho
2 min read
Java Program to Implement Wagner and Fisher Algorithm for Online String Matching
The Wagner-Fischer Algorithm is a dynamic programming algorithm that measures the Levenshtein distance or the edit distance between two strings of characters. Levenshtein Distance(LD) calculates how similar are the two strings. The distance is calculated by three parameters to transform the string1 to string2. The parameters are: Number of deletion
3 min read
Java Program to Implement the RSA Algorithm
RSA or Rivest–Shamir–Adleman is an algorithm employed by modern computers to encrypt and decrypt messages. It is an asymmetric cryptographic algorithm. Asymmetric means that there are two different keys. This is also called public-key cryptography because one among the keys are often given to anyone. The other is the private key which is kept priva
3 min read
Java Program to Implement Levenshtein Distance Computing Algorithm
The Levenshtein distance also called the Edit distance, is the minimum number of operations required to transform one string to another. Typically, three types of operations are performed (one at a time) : Replace a character.Delete a character.Insert a character. Examples: Input: str1 = "glomax", str2 = "folmax" Output: 3 str1 is converted to str2
6 min read
Java Program to Implement the String Search Algorithm for Short Text Sizes
Pattern searching is a crucial problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results. A typical problem statement would be-Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints
4 min read
Java Program to Implement CAS (Compare and Swap) Algorithm
Compare and swap is a technique used when designing concurrent algorithms. The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value, then swap the actual value of the variable for the new value passed in. For understanding the algorithm, one must have the ba
5 min read
Java Program to Implement Playfair Cipher Algorithm
Cipher is an algorithm for encryption and decryption. The cipher text is a process that applies to different types of algorithms to convert plain text to coded text. It is referred to as ciphertext. The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord
6 min read
Java Program to Implement of Gabow Scaling Algorithm
Gabow's Algorithm is a scaling algorithm that aims in solving a problem by initially considering only the highest order bit of each relevant input value (such as an edge weight). Then it refines the initial solution by looking at the two highest-order bits. It progressively looks at more and more high-order bits, refining the solution in each itera
4 min read
Java Program to Implement Zhu–Takaoka String Matching Algorithm
Zhu-Takaoka String Matching Algorithm is a Variant of Boyer Moore Algorithm for Pattern Matching in a String. There is a slight change in the concept of Bad Maps in this algorithm. The concept of Good Suffixes remains as same as that of Boyer Moore's but instead of using a single character for Bad Shifts, now in this algorithm, we will be performin
7 min read
Java Program to Implement Commentz-Walter Algorithm
The Commentz-Walter algorithm is a string-matching algorithm that is used to search for a given pattern in a text string. It is a variant of the Knuth-Morris-Pratt (KMP) algorithm, which is a well-known algorithm for string matching. This algorithm works by preprocessing the pattern string to create a failure function that encodes the information a
6 min read
Java Program to Implement Shunting Yard Algorithm
The shunting yard algorithm is used to convert the infix notation to reverse Polish notation. The postfix notation is also known as the Reverse Polish Notation (RPN). The algorithm was named a “Shunting yard” because its activity is similar to a railroad shunting yard. It is a method for representing expressions in which the operator symbol is plac
6 min read
Java Program to Implement Bowyer-Watson Algorithm
To gain some practical programming experience related to computational geometry topics, we will apply the Bowyer-Watson algorithm that will be able to facilitate the process to some extent. Bowyer-Watson AlgorithmThe Bowyer-Watson algorithm is a computational algorithm for constructing Delaunay triangulations and is also a subclass of computational
4 min read
Java Program to Implement Bellman Ford Algorithm
The Bellman-Ford algorithm is an essential method in graph theory and algorithms used to determine the shortest paths in a weighted graph from one vertex of origin to all other vertexes. This article will cover implementing the Bellman-Ford algorithm in Java language and also explore its intricacies, benefits, and limitations. What is the Bellman-F
6 min read
Java Program to Find GCD and LCM of Two Numbers Using Euclid’s Algorithm
GCD or the Greatest Common Divisor of two given numbers A and B is the highest number dividing both A and B completely, i.e., leaving remainder 0 in each case. LCM or the Least Common Multiple of two given numbers A and B is the Least number which can be divided by both A and B, leaving remainder 0 in each case. The LCM of two numbers can be comput
3 min read
Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range
A number which is divisible by 1 and itself or a number which has factors as 1 and the number itself is called a prime number. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so. Example: Input : from = 1, to = 20 Output: 2 3 5 7 11 13 17 19 Input : from = 4, to = 15
3 min read
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
A prime number is a whole number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23. Given a range, L to R, the task is to generate all the prime numbers that exist in the Range. Examples Input: 1 10 Output 2 3 5 7 Input: 20 30 Output: 23 29 Approach 1: Check every element whether the ele
5 min read
Java Program to Print the Multiplication Table in a Triangle Form
In this form, a table is displayed row and column-wise, in such a way such that in every row, only the entries up to the same column number filled. Example: Input : rows = 6 Output: 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 Approach: The idea is to use nested loops. First, display the column numbers. Then, use a nested loop to fill out t
2 min read
Java Program to Find remainder of array multiplication divided by n
Write a Java program for a given multiple numbers and a number n, the task is to print the remainder after multiplying all the numbers divided by n. Examples: Input: arr[] = {100, 10, 5, 25, 35, 14}, n = 11Output: 9Explanation: 100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9Input : arr[] = {100, 10}, n = 5 Output : 0Explanation: 100 x 10 = 1000 % 5
3 min read
Java Program for Matrix Chain Multiplication | DP-8
Write a Java program for a given dimension of a sequence of matrices in an array arr[], where the dimension of the ith matrix is (arr[i-1] * arr[i]), the task is to find the most efficient way to multiply these matrices together such that the total number of element multiplications is minimum. Examples: Input: arr[] = {40, 20, 30, 10, 30}Output: 26
7 min read
Java Program to Print Multiplication Table for Any Number
Given a number n as input, we need to print its table, where N>0. Example: Input 1: N = 7Output: 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 7 * 10 = 70Ways to Print Multiplication Table for Any Number in JavaFour ways are shown to Print Multiplication Table for any Number: Using for loop for
4 min read
Java Program to Implement Control Table in Java
Control tables will be tables that control the control stream or have a significant influence on program control. There are no unbending guidelines about the structure or substance of a control table—its passing trait is its capacity to coordinate the control stream somehow or another through "execution" by a processor or mediator. The plan of such
3 min read
How to Implement a Bidirectional Map Using Two HashSets in Java?
Bidirectional maps are also known as two-way maps or dual maps. These provide a convenient way to establish a relationship between keys and values in both directions. In Java, we can implement these using HashSet. So, in this article, we will see how to implement bidirectional maps in Java using two Hash Sets. Bidirectional Map Implementation:A bid
4 min read
How to Perform Java Parallel Matrix Multiplication?
In Java, Parallelism can be used to perform Matrix Multiplication using multiple threads concurrently. The major advantage of this technique is that it uses distributed computing environments to speed up the computation. In this article, we will learn how to perform Parallel Matrix Multiplication in Java. Key terminologies: Matrix Multiplication: I
4 min read
Java Program to Implement Circular Buffer
When data is constantly moved from one place to another or from one process to another or is frequently accessed, it cannot be stored in permanent memory locations such as hard drives as they take time to retrieve the data. This type of data needs to be accessed quickly and is stored in temporary memory locations such as RAM known as buffers. Examp
8 min read
Java Program to Implement HashTables with Linear Probing
Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects. Suppose an object is to be assigned a key to it to make searching easy. To store the key/value pair, one can use a simple array like a data structure where keys (integers) can be used directly as an index to store values. However, in cases wh
5 min read
Java Program to Implement Stack API
A stack is a linear data structure that follows a particular order in which insertion/deletion operations are performed. The order is either LIFO(Last In First Out) or FILO(First In Last Out). Stack uses the push() function in order to insert new elements into the Stack and pop() function in order to remove an element from the stack. Insertion and
3 min read
three90RightbarBannerImg