Square of large number represented as String

Given a very large number, the task is to write a program to compute its square.

Examples:

Input: 9999
Output: 99980001
9999*9999 = 99980001



Input: 45454545
Output: 2066115661157025
45454545*45454545 = 2066115661157025

Naive Approach: A naive approach is to calculate the squares my multiplying the number with itself. But in C++, if the input is a large number, the resultant square will overflow.

Efficient Approach: An efficient approach is to store the number as strings, and perform multiplication of two large numbers.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to multiply two numbers
// represented as strings.
#include <bits/stdc++.h>
using namespace std;
  
// Multiplies str1 and str2, and prints result.
string multiply(string num1, string num2)
{
    int n1 = num1.size();
    int n2 = num2.size();
    if (n1 == 0 || n2 == 0)
        return "0";
  
    // will keep the result number in vector
    // in reverse order
    vector<int> result(n1 + n2, 0);
  
    // Below two indexes are used to find positions
    // in result.
    int i_n1 = 0;
    int i_n2 = 0;
  
    // Go from right to left in num1
    for (int i = n1 - 1; i >= 0; i--) {
        int carry = 0;
        int n1 = num1[i] - '0';
  
        // To shift position to left after every
        // multiplication of a digit in num2
        i_n2 = 0;
  
        // Go from right to left in num2
        for (int j = n2 - 1; j >= 0; j--) {
            // Take current digit of second number
            int n2 = num2[j] - '0';
  
            // Multiply with current digit of first number
            // and add result to previously stored result
            // at current position.
            int sum = n1 * n2 + result[i_n1 + i_n2] + carry;
  
            // Carry for next iteration
            carry = sum / 10;
  
            // Store result
            result[i_n1 + i_n2] = sum % 10;
  
            i_n2++;
        }
  
        // store carry in next cell
        if (carry > 0)
            result[i_n1 + i_n2] += carry;
  
        // To shift position to left after every
        // multiplication of a digit in num1.
        i_n1++;
    }
  
    // ignore '0's from the right
    int i = result.size() - 1;
    while (i >= 0 && result[i] == 0)
        i--;
  
    // If all were '0's - means either both or
    // one of num1 or num2 were '0'
    if (i == -1)
        return "0";
  
    // generate the result string
    string s = "";
    while (i >= 0)
        s += std::to_string(result[i--]);
  
    return s;
}
  
// Driver code
int main()
{
    string str1 = "454545454545454545";
  
    cout << multiply(str1, str1);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to multiply two numbers 
// represented as strings.
  
class GFG 
{
  
    // Multiplies str1 and str2, and prints result.
    public static String multiply(String num1, String num2)
    {
        int n1 = num1.length();
        int n2 = num2.length();
        if (n1 == 0 || n2 == 0)
            return "0";
  
        // will keep the result number in vector
        // in reverse order
        int[] result = new int[n1 + n2];
  
        // Below two indexes are used to find positions
        // in result.
        int i_n1 = 0;
        int i_n2 = 0;
  
        // Go from right to left in num1
        for (int i = n1 - 1; i >= 0; i--) 
        {
            int carry = 0;
            int n_1 = num1.charAt(i) - '0';
  
            // To shift position to left after every
            // multiplication of a digit in num2
            i_n2 = 0;
  
            // Go from right to left in num2
            for (int j = n2 - 1; j >= 0; j--)
            {
  
                // Take current digit of second number
                int n_2 = num2.charAt(j) - '0';
  
                // Multiply with current digit of first number
                // and add result to previously stored result
                // at current position.
                int sum = n_1 * n_2 + result[i_n1 + i_n2] + carry;
  
                // Carry for next iteration
                carry = sum / 10;
  
                // Store result
                result[i_n1 + i_n2] = sum % 10;
  
                i_n2++;
            }
  
            // store carry in next cell
            if (carry > 0)
                result[i_n1 + i_n2] += carry;
  
            // To shift position to left after every
            // multiplication of a digit in num1.
            i_n1++;
        }
  
        // ignore '0's from the right
        int i = result.length - 1;
        while (i >= 0 && result[i] == 0)
            i--;
  
        // If all were '0's - means either both or
        // one of num1 or num2 were '0'
        if (i == -1)
            return "0";
  
        // generate the result string
        String s = "";
        while (i >= 0)
            s += Integer.toString(result[i--]);
  
        return s;
    }
  
    // Driver code
    public static void main(String[] args) 
    {
        String str1 = "454545454545454545";
        System.out.println(multiply(str1, str1));
  
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to multiply two numbers 
// represented as strings.
using System;
using System.Collections.Generic;
      
class GFG 
{
  
    // Multiplies str1 and str2, 
    // and prints result.
    public static String multiply(String num1, 
                                  String num2)
    {
        int n1 = num1.Length;
        int n2 = num2.Length;
        if (n1 == 0 || n2 == 0)
            return "0";
  
        // will keep the result number in vector
        // in reverse order
        int[] result = new int[n1 + n2];
  
        // Below two indexes are used to 
        // find positions in result.
        int i_n1 = 0;
        int i_n2 = 0;
        int i = 0;
          
        // Go from right to left in num1
        for (i = n1 - 1; i >= 0; i--) 
        {
            int carry = 0;
            int n_1 = num1[i] - '0';
  
            // To shift position to left after every
            // multiplication of a digit in num2
            i_n2 = 0;
  
            // Go from right to left in num2
            for (int j = n2 - 1; j >= 0; j--)
            {
  
                // Take current digit of second number
                int n_2 = num2[j] - '0';
  
                // Multiply with current digit of first number
                // and add result to previously stored result
                // at current position.
                int sum = n_1 * n_2 + 
                          result[i_n1 + i_n2] + carry;
  
                // Carry for next iteration
                carry = sum / 10;
  
                // Store result
                result[i_n1 + i_n2] = sum % 10;
  
                i_n2++;
            }
  
            // store carry in next cell
            if (carry > 0)
                result[i_n1 + i_n2] += carry;
  
            // To shift position to left after every
            // multiplication of a digit in num1.
            i_n1++;
        }
  
        // ignore '0's from the right
        i = result.Length - 1;
        while (i >= 0 && result[i] == 0)
            i--;
  
        // If all were '0's - means either both or
        // one of num1 or num2 were '0'
        if (i == -1)
            return "0";
  
        // generate the result string
        String s = "";
        while (i >= 0)
            s += (result[i--]).ToString();
  
        return s;
    }
  
    // Driver code
    public static void Main(String[] args) 
    {
        String str1 = "454545454545454545";
        Console.WriteLine(multiply(str1, str1));
    }
}
  
// This code is contributed by Princi Singh

chevron_right


Output:

206611570247933883884297520661157025


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : sanjeev2552, princi singh



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.