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
def multiply ( num1 , num2 ) : NEW_LINE INDENT n1 = len ( num1 ) NEW_LINE n2 = len ( num2 ) NEW_LINE if ( n1 == 0 or n2 == 0 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT result = [ 0 ] * ( n1 + n2 ) NEW_LINE i_n1 = 0 NEW_LINE i_n2 = 0 NEW_LINE for i in range ( n1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT carry = 0 NEW_LINE n_1 = ord ( num1 [ i ] ) - ord ( '0' ) NEW_LINE i_n2 = 0 NEW_LINE for j in range ( n2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT n_2 = ord ( num2 [ j ] ) - ord ( '0' ) NEW_LINE sum = n_1 * n_2 + result [ i_n1 + i_n2 ] + carry NEW_LINE carry = sum // 10 NEW_LINE result [ i_n1 + i_n2 ] = sum % 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 += str ( result [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = "454545454545454545" NEW_LINE print ( multiply ( str1 , str1 ) ) NEW_LINE DEDENT