Square of large number represented as String | Multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multiplication of a digit in num2 ; Go from right to left in num2 ; Take current digit of second number ; Multiply with current digit of first number and add result to previously stored result at current position . ; Carry for next iteration ; Store result ; store carry in next cell ; To shift position to left after every multiplication of a digit in num1 . ; ignore '0' s from the right ; If all were '0' s - means either both or one of num1 or num2 were '0' ; generate the result string ; Driver code
function multiply ( num1 , num2 ) { let n1 = num1 . length ; let n2 = num2 . length ; if ( n1 == 0 n2 == 0 ) return " " ; let result = new Array ( n1 + n2 ) ; for ( let i = 0 ; i < result . length ; i ++ ) { result [ i ] = 0 ; } let i_n1 = 0 ; let i_n2 = 0 ; for ( let i = n1 - 1 ; i >= 0 ; i -- ) { let carry = 0 ; let n_1 = num1 [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; i_n2 = 0 ; for ( let j = n2 - 1 ; j >= 0 ; j -- ) { let n_2 = num2 [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; let sum = n_1 * n_2 + result [ i_n1 + i_n2 ] + carry ; carry = Math . floor ( sum / 10 ) ; result [ i_n1 + i_n2 ] = sum % 10 ; i_n2 ++ ; } if ( carry > 0 ) result [ i_n1 + i_n2 ] += carry ; i_n1 ++ ; } let i = result . length - 1 ; while ( i >= 0 && result [ i ] == 0 ) i -- ; if ( i == - 1 ) return " " ; let s = " " ; while ( i >= 0 ) s += ( result [ i -- ] ) . toString ( ) ; return s ; } let str1 = " " ; document . write ( multiply ( str1 , str1 ) ) ;