Multiply Large Numbers represented as Strings | 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
def multiply ( num1 , num2 ) : NEW_LINE INDENT len1 = len ( num1 ) NEW_LINE len2 = len ( num2 ) NEW_LINE if len1 == 0 or len2 == 0 : NEW_LINE INDENT return "0" NEW_LINE DEDENT result = [ 0 ] * ( len1 + len2 ) NEW_LINE i_n1 = 0 NEW_LINE i_n2 = 0 NEW_LINE for i in range ( len1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT carry = 0 NEW_LINE n1 = ord ( num1 [ i ] ) - 48 NEW_LINE i_n2 = 0 NEW_LINE for j in range ( len2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT n2 = ord ( num2 [ j ] ) - 48 NEW_LINE summ = n1 * n2 + result [ i_n1 + i_n2 ] + carry NEW_LINE carry = summ // 10 NEW_LINE result [ i_n1 + i_n2 ] = summ % 10 NEW_LINE i_n2 += 1 NEW_LINE DEDENT if ( carry > 0 ) : NEW_LINE INDENT result [ i_n1 + i_n2 ] += carry NEW_LINE DEDENT i_n1 += 1 NEW_LINE DEDENT i = len ( result ) - 1 NEW_LINE while ( i >= 0 and result [ i ] == 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( i == - 1 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT s = " " NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT s += chr ( result [ i ] + 48 ) NEW_LINE i -= 1 NEW_LINE DEDENT return s NEW_LINE DEDENT str1 = "1235421415454545454545454544" NEW_LINE str2 = "1714546546546545454544548544544545" NEW_LINE if ( ( str1 [ 0 ] == ' - ' or str2 [ 0 ] == ' - ' ) and ( str1 [ 0 ] != ' - ' or str2 [ 0 ] != ' - ' ) ) : NEW_LINE INDENT print ( " - " , end = ' ' ) NEW_LINE DEDENT if ( str1 [ 0 ] == ' - ' and str2 [ 0 ] != ' - ' ) : NEW_LINE INDENT str1 = str1 [ 1 : ] NEW_LINE DEDENT elif ( str1 [ 0 ] != ' - ' and str2 [ 0 ] == ' - ' ) : NEW_LINE INDENT str2 = str2 [ 1 : ] NEW_LINE DEDENT elif ( str1 [ 0 ] == ' - ' and str2 [ 0 ] == ' - ' ) : NEW_LINE INDENT str1 = str1 [ 1 : ] NEW_LINE str2 = str2 [ 1 : ] NEW_LINE DEDENT print ( multiply ( str1 , str2 ) ) NEW_LINE