Given two positive numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find product of these two numbers.
Examples:
Input : num1 = 4154
num2 = 51454
Output : 213739916
Input : num1 = 654154154151454545415415454
num2 = 63516561563156316545145146514654
Output : 41549622603955309777243716069997997007620439937711509062916
The idea is based on school mathematics.

We start from last digit of second number multiply it with first number. Then we multiply second digit of second number with first number, and so on. We add all these multiplications. While adding, we put i-th multiplication shifted.
The approach used in below solution is to keep only one array for result. We traverse all digits first and second numbers in a loop and add the result at appropriate position.
C++
#include<bits/stdc++.h>
using namespace std;
string multiply(string num1, string num2)
{
int len1 = num1.size();
int len2 = num2.size();
if (len1 == 0 || len2 == 0)
return "0" ;
vector< int > result(len1 + len2, 0);
int i_n1 = 0;
int i_n2 = 0;
for ( int i=len1-1; i>=0; i--)
{
int carry = 0;
int n1 = num1[i] - '0' ;
i_n2 = 0;
for ( int j=len2-1; j>=0; j--)
{
int n2 = num2[j] - '0' ;
int sum = n1*n2 + result[i_n1 + i_n2] + carry;
carry = sum/10;
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
if (carry > 0)
result[i_n1 + i_n2] += carry;
i_n1++;
}
int i = result.size() - 1;
while (i>=0 && result[i] == 0)
i--;
if (i == -1)
return "0" ;
string s = "" ;
while (i >= 0)
s += std::to_string(result[i--]);
return s;
}
int main()
{
string str1 = "1235421415454545454545454544" ;
string str2 = "1714546546546545454544548544544545" ;
if ((str1.at(0) == '-' || str2.at(0) == '-' ) &&
(str1.at(0) != '-' || str2.at(0) != '-' ))
cout<< "-" ;
if (str1.at(0) == '-' )
str1 = str1.substr(1);
if (str2.at(0) == '-' )
str2 = str2.substr(1);
cout << multiply(str1, str2);
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG
{
static String multiply(String num1, String num2)
{
int len1 = num1.length();
int len2 = num2.length();
if (len1 == 0 || len2 == 0 )
return "0" ;
int result[] = new int [len1 + len2];
int i_n1 = 0 ;
int i_n2 = 0 ;
for ( int i = len1 - 1 ; i >= 0 ; i--)
{
int carry = 0 ;
int n1 = num1.charAt(i) - '0' ;
i_n2 = 0 ;
for ( int j = len2 - 1 ; j >= 0 ; j--)
{
int n2 = num2.charAt(j) - '0' ;
int sum = n1 * n2 + result[i_n1 + i_n2] + carry;
carry = sum / 10 ;
result[i_n1 + i_n2] = sum % 10 ;
i_n2++;
}
if (carry > 0 )
result[i_n1 + i_n2] += carry;
i_n1++;
}
int i = result.length - 1 ;
while (i >= 0 && result[i] == 0 )
i--;
if (i == - 1 )
return "0" ;
String s = "" ;
while (i >= 0 )
s += (result[i--]);
return s;
}
public static void main(String[] args)
{
String str1 = "1235421415454545454545454544" ;
String str2 = "1714546546546545454544548544544545" ;
if ((str1.charAt( 0 ) == '-' || str2.charAt( 0 ) == '-' ) &&
(str1.charAt( 0 ) != '-' || str2.charAt( 0 ) != '-' ))
System.out.print( "-" );
if (str1.charAt( 0 ) == '-' )
str1 = str1.substring( 1 );
if (str2.charAt( 0 ) == '-' )
str2 = str2.substring( 1 );
System.out.println(multiply(str1, str2));
}
}
|
Python3
def multiply(num1, num2):
len1 = len (num1)
len2 = len (num2)
if len1 = = 0 or len2 = = 0 :
return "0"
result = [ 0 ] * (len1 + len2)
i_n1 = 0
i_n2 = 0
for i in range (len1 - 1 , - 1 , - 1 ):
carry = 0
n1 = ord (num1[i]) - 48
i_n2 = 0
for j in range (len2 - 1 , - 1 , - 1 ):
n2 = ord (num2[j]) - 48
summ = n1 * n2 + result[i_n1 + i_n2] + carry
carry = summ / / 10
result[i_n1 + i_n2] = summ % 10
i_n2 + = 1
if (carry > 0 ):
result[i_n1 + i_n2] + = carry
i_n1 + = 1
i = len (result) - 1
while (i > = 0 and result[i] = = 0 ):
i - = 1
if (i = = - 1 ):
return "0"
s = ""
while (i > = 0 ):
s + = chr (result[i] + 48 )
i - = 1
return s
str1 = "1235421415454545454545454544"
str2 = "1714546546546545454544548544544545"
if ((str1[ 0 ] = = '-' or str2[ 0 ] = = '-' ) and
(str1[ 0 ] ! = '-' or str2[ 0 ] ! = '-' )):
print ( "-" , end = '')
if (str1[ 0 ] = = '-' and str2[ 0 ] ! = '-' ):
str1 = str1[ 1 :]
elif (str1[ 0 ] ! = '-' and str2[ 0 ] = = '-' ):
str2 = str2[ 1 :]
elif (str1[ 0 ] = = '-' and str2[ 0 ] = = '-' ):
str1 = str1[ 1 :]
str2 = str2[ 1 :]
print (multiply(str1, str2))
|
C#
using System;
class GFG
{
static String multiply(String num1, String num2)
{
int len1 = num1.Length;
int len2 = num2.Length;
if (len1 == 0 || len2 == 0)
return "0" ;
int []result = new int [len1 + len2];
int i_n1 = 0;
int i_n2 = 0;
int i;
for (i = len1 - 1; i >= 0; i--)
{
int carry = 0;
int n1 = num1[i] - '0' ;
i_n2 = 0;
for ( int j = len2 - 1; j >= 0; j--)
{
int n2 = num2[j] - '0' ;
int sum = n1 * n2 + result[i_n1 + i_n2] + carry;
carry = sum / 10;
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
if (carry > 0)
result[i_n1 + i_n2] += carry;
i_n1++;
}
i = result.Length - 1;
while (i >= 0 && result[i] == 0)
i--;
if (i == -1)
return "0" ;
String s = "" ;
while (i >= 0)
s += (result[i--]);
return s;
}
public static void Main(String[] args)
{
String str1 = "1235421415454545454545454544" ;
String str2 = "1714546546546545454544548544544545" ;
if ((str1[0] == '-' || str2[0] == '-' ) &&
(str1[0] != '-' || str2[0] != '-' ))
Console.Write( "-" );
if (str1[0] == '-' && str2[0] != '-' )
{
str1 = str1.Substring(1);
}
else if (str1[0] != '-' && str2[0] == '-' )
{
str2 = str2.Substring(1);
}
else if (str1[0] == '-' && str2[0] == '-' )
{
str1 = str1.Substring(1);
str2 = str2.Substring(1);
}
Console.WriteLine(multiply(str1, str2));
}
}
|
Javascript
function multiply(num1, num2)
{
let len1 = num1.length;
let len2 = num2.length;
if (len1 == 0 || len2 == 0)
return "0"
let result = new Array(len1 + len2).fill(0)
let i_n1 = 0
let i_n2 = 0
for ( var i = len1 - 1; i > -1 ; i --)
{
let carry = 0
let n1 = (num1[i]).charCodeAt(0) - 48
i_n2 = 0
for ( var j = len2 - 1; j > -1; j--)
{
let n2 = (num2[j]).charCodeAt(0) - 48
let summ = n1 * n2 + result[i_n1 + i_n2] + carry
carry = Math.floor(summ / 10)
result[i_n1 + i_n2] = summ % 10
i_n2 += 1
}
if (carry > 0)
result[i_n1 + i_n2] += carry
i_n1 += 1
}
i = result.length - 1
while (i >= 0 && result[i] == 0)
i -= 1
if (i == -1)
return "0"
let s = ""
while (i >= 0)
{
s += String.fromCharCode(result[i] + 48)
i -= 1
}
return s
}
let str1 = "1235421415454545454545454544"
let str2 = "1714546546546545454544548544544545"
if ((str1[0] == '-' || str2[0] == '-' ) &&
(str1[0] != '-' || str2[0] != '-' ))
process.stdout.write( "-" )
if (str1[0] == '-' && str2[0] != '-' )
str1.shift()
else if (str1[0] != '-' && str2[0] == '-' )
str2.shift()
else if (str1[0] == '-' && str2[0] == '-' )
{
str1.shift()
str2.shift()
}
console.log(multiply(str1, str2))
|
Output:
2118187521397235888154583183918321221520083884298838480662480
The above code is adapted from the code provided by Gaurav.
Time Complexity: O(m*n), where m and n are length of two number that need to be multiplied.
Auxiliary Space: O(m+n), where m and n are length of two number that need to be multiplied.
The Way to understand:
The Approach:
Compute the ones-digit, then the tens-digit, then the hundreds-digit, etc. For example when multiplying 1234 with 5678, the thousands-digit of the product is 4*5 + 3*6 + 2*7 + 1*8 (plus what got carried from the hundreds-digit).
C++
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
string a = "1235421415454545454545454544" ;
string b = "1714546546546545454544548544544545" ;
if (a== "0" || b== "0" ){
cout<<0<<endl;
return 0;
}
int m = a.size() - 1, n = b.size() - 1, carry = 0;
string product;
for ( int i=0; i<=m+n || carry; ++i) {
for ( int j=max(0, i-n); j<=min(i, m); ++j)
carry += (a[m-j] - '0' ) * (b[n-i+j] - '0' );
product += carry % 10 + '0' ;
carry /= 10;
}
reverse(begin(product), end(product));
cout<< "The Product is: " ;
cout<<product<<endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
String a = "1235421415454545454545454544" ;
String b = "1714546546546545454544548544544545" ;
if (a.equals( "0" ) || b.equals( "0" )) {
System.out.println( "0" );
return ;
}
int m = a.length() - 1 , n = b.length() - 1 ,
carry = 0 ;
String product = "" ;
for ( int i = 0 ; i <= m + n || carry != 0 ; ++i) {
for ( int j = Math.max( 0 , i - n);
j <= Math.min(i, m); ++j) {
carry += (a.charAt(m - j) - '0' )
* (b.charAt(n - i + j) - '0' );
}
product += ( char )(carry % 10 + '0' );
carry /= 10 ;
}
product = new StringBuilder(product)
.reverse()
.toString();
System.out.println( "The Product is: " + product);
}
}
|
Python3
def multiply_strings(a, b):
if a = = "0" or b = = "0" :
return "0"
m, n = len (a) - 1 , len (b) - 1
carry = 0
product = ""
for i in range ( 0 , m + n + 1 ):
for j in range ( max ( 0 , i - n), min (i, m) + 1 ):
carry + = ( ord (a[m - j]) - 48 ) * ( ord (b[n - i + j]) - 48 )
product + = str (carry % 10 )
carry / / = 10
return product[:: - 1 ]
if __name__ = = '__main__' :
a = "1235421415454545454545454544"
b = "1714546546546545454544548544544545"
product = multiply_strings(a, b)
print ( "The Product is: " + product)
|
Javascript
function multiplyStrings(a, b) {
if (a === "0" || b === "0" ) {
return "0" ;
}
let m = a.length - 1;
let n = b.length - 1;
let carry = 0;
let product = "" ;
for (let i = 0; i <= m + n; i++) {
for (let j = Math.max(0, i - n); j <= Math.min(i, m); j++) {
carry += (a[m - j].charCodeAt(0) - 48) * (b[n - i + j].charCodeAt(0) - 48);
}
product += (carry % 10).toString();
carry = Math.floor(carry / 10);
}
return product.split( "" ).reverse().join( "" );
}
const a = "1235421415454545454545454544" ;
const b = "1714546546546545454544548544544545" ;
const product = multiplyStrings(a, b);
console.log( "The Product is: " + product);
|
C#
using System;
public class Mainn {
public static void Main( string [] args) {
string a = "1235421415454545454545454544" ;
string b = "1714546546546545454544548544544545" ;
if (a.Equals( "0" ) || b.Equals( "0" )) {
Console.WriteLine( "0" );
return ;
}
int m = a.Length - 1, n = b.Length - 1,
carry = 0;
string product = "" ;
for ( int i = 0; i <= m + n || carry != 0; ++i) {
for ( int j = Math.Max(0, i - n);
j <= Math.Min(i, m); ++j) {
carry += (a[m - j] - '0' )
* (b[n - i + j] - '0' );
}
product += ( char )(carry % 10 + '0' );
carry /= 10;
}
char [] charArray = product.ToCharArray();
Array.Reverse(charArray);
product = new string (charArray);
Console.WriteLine( "The Product is: " + product);
}
}
|
Time Complexity: O(m*n), where m and n are length of two number that need to be multiplied.
Auxiliary Space: O(m+n), where m and n are length of two number that need to be multiplied.
Method 2:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string num1 = "1235421415454545454545454544" ;
string tempnum1 = num1;
string num2 = "1714546546546545454544548544544545" ;
string tempnum2 = num2;
if (num1[0] == '-' && num2[0] != '-' ) {
num1 = num1.substr(1);
}
else if (num1[0] != '-' && num2[0] == '-' ) {
num2 = num2.substr(1);
}
else if (num1[0] == '-' && num2[0] == '-' ) {
num1 = num1.substr(1);
num2 = num2.substr(1);
}
string s1 = num1;
string s2 = num2;
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
vector< int > m(s1.length() + s2.length());
for ( int i = 0; i < s1.length(); i++) {
for ( int j = 0; j < s2.length(); j++) {
m[i + j]
= m[i + j] + (s1[i] - '0' ) * (s2[j] - '0' );
}
}
string product = "" ;
for ( int i = 0; i < m.size(); i++) {
int digit = m[i] % 10;
int carry = m[i] / 10;
if (i + 1 < m.size()) {
m[i + 1] = m[i + 1] + carry;
}
product = to_string(digit) + product;
}
while (product.length() > 1 && product[0] == '0' ) {
product = product.substr(1);
}
if (tempnum1[0] == '-' && tempnum2[0] != '-' ) {
product = "-" + product;
}
else if (tempnum1[0] != '-' && tempnum2[0] == '-' ) {
product = "-" + product;
}
cout << "Product of the two numbers is :"
<< "\n"
<< product << endl;
}
|
Java
import java.util.Scanner;
public class StringMultiplication {
public static void main(String[] args)
{
String num1 = "1235421415454545454545454544" ;
String tempnum1 = num1;
String num2 = "1714546546546545454544548544544545" ;
String tempnum2 = num2;
if (num1.charAt( 0 ) == '-'
&& num2.charAt( 0 ) != '-' ) {
num1 = num1.substring( 1 );
}
else if (num1.charAt( 0 ) != '-'
&& num2.charAt( 0 ) == '-' ) {
num2 = num2.substring( 1 );
}
else if (num1.charAt( 0 ) == '-'
&& num2.charAt( 0 ) == '-' ) {
num1 = num1.substring( 1 );
num2 = num2.substring( 1 );
}
String s1
= new StringBuffer(num1).reverse().toString();
String s2
= new StringBuffer(num2).reverse().toString();
int [] m = new int [s1.length() + s2.length()];
for ( int i = 0 ; i < s1.length(); i++) {
for ( int j = 0 ; j < s2.length(); j++) {
m[i + j] = m[i + j]
+ (s1.charAt(i) - '0' )
* (s2.charAt(j) - '0' );
}
}
String product = new String();
for ( int i = 0 ; i < m.length; i++) {
int digit = m[i] % 10 ;
int carry = m[i] / 10 ;
if (i + 1 < m.length) {
m[i + 1 ] = m[i + 1 ] + carry;
}
product = digit + product;
}
while (product.length() > 1
&& product.charAt( 0 ) == '0' ) {
product = product.substring( 1 );
}
if (tempnum1.charAt( 0 ) == '-'
&& tempnum2.charAt( 0 ) != '-' ) {
product = new StringBuffer(product)
.insert( 0 , '-' )
.toString();
}
else if (tempnum1.charAt( 0 ) != '-'
&& tempnum2.charAt( 0 ) == '-' ) {
product = new StringBuffer(product)
.insert( 0 , '-' )
.toString();
}
else if (tempnum1.charAt( 0 ) == '-'
&& tempnum2.charAt( 0 ) == '-' ) {
product = product;
}
System.out.println( "Product of the two numbers is :"
+ "\n" + product);
}
}
|
Python3
def reverse(s):
str = ""
for i in s:
str = i + str
return str
num1 = "1235421415454545454545454544"
tempnum1 = num1
num2 = "1714546546546545454544548544544545"
tempnum2 = num2
if (num1[ 0 ] = = '-' and num2[ 0 ] ! = '-' ):
num1 = num1[ 1 :]
elif (num1[ 0 ] ! = '-' and num2[ 0 ] = = '-' ):
num2 = num2[ 1 :]
elif (num1[ 0 ] = = '-' and num2[ 0 ] = = '-' ):
num1 = num1[ 1 :]
num2 = num2[ 1 :]
s1 = num1
s2 = num2
s1 = reverse(s1)
s2 = reverse(s2)
m = [ 0 ] * ( len (s1) + len (s2))
for i in range ( len (s1)):
for j in range ( len (s2)):
m[i + j] = m[i + j] + ( ord (s1[i]) - 48 ) * ( ord (s2[j]) - 48 )
product = ""
for i in range ( len (m)):
digit = m[i] % 10
carry = m[i] / / 10
if (i + 1 < len (m)):
m[i + 1 ] = m[i + 1 ] + carry
product = str (digit) + product
while ( len (product) > 1 and product[ 0 ] = = '0' ):
product = product[ 1 :]
if (tempnum1[ 0 ] = = '-' and tempnum2[ 0 ] ! = '-' ):
product = "-" + product
elif (tempnum1[ 0 ] ! = '-' and tempnum2[ 0 ] = = '-' ):
product = "-" + product
print ( "Product of the two numbers is :" )
print (product)
|
C#
using System;
using System.Text;
using System.Linq;
public class GFG{
static public void Main (){
String num1 = "1235421415454545454545454544" ;
String tempnum1 = num1;
String num2 = "1714546546546545454544548544544545" ;
String tempnum2 = num2;
if (num1[0] == '-' && num2[0] != '-' ) {
num1 = num1.Substring(1);
} else {
if (num1[0] != '-' && num2[0] == '-' ) {
num2 = num2.Substring(1);
} else {
if (num1[0] == '-' && num2[0] == '-' ) {
num1 = num1.Substring(1);
num2 = num2.Substring(1);
}
}
}
String s1 = new string (num1.Reverse().ToArray());
String s2 = new string (num2.Reverse().ToArray());
int [] m = new int [s1.Length + s2.Length];
for ( int i = 0; i < s1.Length; i++) {
for ( int j = 0; j < s2.Length; j++) {
int x = int .Parse((s1[i]- '0' ).ToString());
int y = int .Parse((s2[j]- '0' ).ToString());
m[i + j] += (x*y);
}
}
String product = "" ;
for ( int i = 0; i < m.Length; i++) {
int digit = m[i] % 10;
int carry = m[i] / 10;
if (i + 1 < m.Length) {
m[i + 1] += carry;
}
product = digit.ToString() + product;
}
while (product.Length > 1 && product[0] == '0' ) {
product = product.Substring(1);
}
if (tempnum1[0] == '-' && tempnum2[0] != '-' ) {
product = new StringBuilder(product).Insert(0, '-' ).ToString();
} else {
if (tempnum1[0] != '-' && tempnum2[0] == '-' ) {
product = new StringBuilder(product).Insert(0, '-' ).ToString();
}
}
Console.Write( "Product of the two numbers is :\n" + product);
}
}
|
Javascript
let num1 = "1235421415454545454545454544" ;
let tempnum1 = num1;
let num2 = "1714546546546545454544548544544545" ;
let tempnum2 = num2;
if (num1[0] == '-' && num2[0] != '-' ) {
num1 = num1.substring(1);
}
else if (num1[0] != '-' && num2[0] == '-' ) {
num2 = num2.substring(1);
}
else if (num1[0] == '-' && num2[0] == '-' ) {
num1 = num1.substring(1);
num2 = num2.substring(1);
}
let s1 = num1.split( "" );
let s2 = num2.split( "" );
s1.reverse();
s2.reverse();
let m = new Array(s1.length + s2.length).fill(0);
for ( var i = 0; i < s1.length; i++)
{
for ( var j = 0; j < s2.length; j++) {
m[i + j] = m[i + j]
+ (parseInt(s1[i]) * (parseInt(s2[j])));
}
}
let product = "" ;
for ( var i = 0; i < m.length; i++) {
let digit = m[i] % 10;
let carry = Math.floor(m[i] / 10);
if (i + 1 < m.length) {
m[i + 1] = m[i + 1] + carry;
}
product = digit.toString() + product;
}
while (product.length > 1 && product[0] == '0' ) {
product = product.substring(1);
}
if (tempnum1[0] == '-' && tempnum2[0] != '-' ) {
product = "-" + product;
}
else if (tempnum1[0] != '-' && tempnum2[0] == '-' ) {
product = "-" + product;
}
console.log( "Product of the two numbers is :" );
console.log(product);
|
OutputProduct of the two numbers is :
2118187521397235888154583183918321221520083884298838480662480
Time Complexity: O(m*n), where m and n are length of two number that need to be multiplied.
Auxiliary Space: O(m+n), where m and n are length of two number that need to be multiplied.
Method 3:
- Convert the two input numbers from strings to lists of integers.
- A list with zeros.
- Iterate over each digit in the second number (num2) from right to left.
- For each digit, multiply it with each digit in the first number num1, and add the result in the result list.
- Convert the result list to a string.
C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string multiply(string num1, string num2) {
vector< int > vec1(num1.size());
for ( int i = 0; i < num1.size(); i++) {
vec1[i] = num1[num1.size() - i - 1] - '0' ;
}
vector< int > vec2(num2.size());
for ( int i = 0; i < num2.size(); i++) {
vec2[i] = num2[num2.size() - i - 1] - '0' ;
}
vector< int > result(vec1.size() + vec2.size());
for ( int i = 0; i < vec2.size(); i++) {
int carry = 0;
for ( int j = 0; j < vec1.size(); j++) {
int product = vec1[j] * vec2[i] + carry + result[i + j];
carry = product / 10;
result[i + j] = product % 10;
}
result[i + vec1.size()] = carry;
}
while (result.size() > 1 && result.back() == 0) {
result.pop_back();
}
string str(result.size(), '0' );
for ( int i = 0; i < result.size(); i++) {
str[result.size() - i - 1] = result[i] + '0' ;
}
return str;
}
int main() {
string num1 = "4154" ;
string num2 = "51454" ;
cout << multiply(num1, num2) << endl;
num1 = "654154154151454545415415454" ;
num2 = "63516561563156316545145146514654" ;
cout << multiply(num1, num2) << endl;
return 0;
}
|
Java
public class MultiplyStrings {
public static String multiply(String num1, String num2) {
int [] n1 = new int [num1.length()];
int [] n2 = new int [num2.length()];
for ( int i = 0 ; i < num1.length(); i++) {
n1[i] = num1.charAt(num1.length() - 1 - i) - '0' ;
}
for ( int i = 0 ; i < num2.length(); i++) {
n2[i] = num2.charAt(num2.length() - 1 - i) - '0' ;
}
int [] result = new int [num1.length() + num2.length()];
for ( int i = 0 ; i < n2.length; i++) {
int carry = 0 ;
for ( int j = 0 ; j < n1.length; j++) {
int product = n1[j] * n2[i] + carry + result[i + j];
carry = product / 10 ;
result[i + j] = product % 10 ;
}
result[i + n1.length] = carry;
}
StringBuilder sb = new StringBuilder();
int i = result.length - 1 ;
while (i > 0 && result[i] == 0 ) {
i--;
}
while (i >= 0 ) {
sb.append(result[i--]);
}
return sb.toString();
}
public static void main(String[] args) {
String num1 = "4154" ;
String num2 = "51454" ;
System.out.println(multiply(num1, num2));
num1 = "654154154151454545415415454" ;
num2 = "63516561563156316545145146514654" ;
System.out.println(multiply(num1, num2));
}
}
|
Python3
def multiply(num1, num2):
num1 = [ int (digit) for digit in num1][:: - 1 ]
num2 = [ int (digit) for digit in num2][:: - 1 ]
result = [ 0 ] * ( len (num1) + len (num2))
for i, digit2 in enumerate (num2):
carry = 0
for j, digit1 in enumerate (num1):
product = digit1 * digit2 + carry + result[i + j]
carry = product / / 10
result[i + j] = product % 10
result[i + len (num1)] = carry
result = result[:: - 1 ]
while len (result) > 1 and result[ - 1 ] = = 0 :
result.pop()
return ''.join( str (digit) for digit in result)
num1 = "4154"
num2 = "51454"
print (multiply(num1, num2))
num1 = "654154154151454545415415454"
num2 = "63516561563156316545145146514654"
print (multiply(num1, num2))
|
Javascript
function multiply(num1, num2) {
let vec1 = num1.split( "" ).reverse().map(Number);
let vec2 = num2.split( "" ).reverse().map(Number);
let result = Array(vec1.length + vec2.length).fill(0);
for (let i = 0; i < vec2.length; i++) {
let carry = 0;
for (let j = 0; j < vec1.length; j++) {
let product = vec1[j] * vec2[i] + carry + result[i + j];
carry = Math.floor(product / 10);
result[i + j] = product % 10;
}
result[i + vec1.length] = carry;
}
while (result.length > 1 && result[result.length - 1] === 0) {
result.pop();
}
let str = result.reverse().join( "" );
return str;
}
let Num1 = "4154" ;
let Num2 = "51454" ;
console.log(multiply(Num1, Num2));
let num1 = "654154154151454545415415454" ;
let num2 = "63516561563156316545145146514654" ;
console.log(multiply(num1, num2));
|
C#
using System;
using System.Linq;
public class Program
{
public static string Multiply( string num1, string num2)
{
int [] vec1 = num1.Reverse().Select(c => c - '0' ).ToArray();
int [] vec2 = num2.Reverse().Select(c => c - '0' ).ToArray();
int [] result = new int [vec1.Length + vec2.Length];
for ( int i = 0; i < vec2.Length; i++)
{
int carry = 0;
for ( int j = 0; j < vec1.Length; j++)
{
int product = vec1[j] * vec2[i] + carry + result[i + j];
carry = product / 10;
result[i + j] = product % 10;
}
result[i + vec1.Length] = carry;
}
while (result.Length > 1 && result[result.Length - 1] == 0)
{
Array.Resize( ref result, result.Length - 1);
}
string str = new string (result.Reverse().Select(d => ( char )(d + '0' )).ToArray());
return str;
}
public static void Main()
{
string num1 = "4154" ;
string num2 = "51454" ;
Console.WriteLine(Multiply(num1, num2));
string num3 = "654154154151454545415415454" ;
string num4 = "63516561563156316545145146514654" ;
Console.WriteLine(Multiply(num3, num4));
}
}
|
Output213739916
41549622603955309777243716069997997007620439937711509062916
Time Complexity: O(m*n), where m and n are length of two number that need to be multiplied.
Auxiliary Space: O(m+n), where m and n are length of two number that need to be multiplied.
Related Article :
Karatsuba algorithm for fast multiplication
This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.