Java program to multiply large numbers has been shown here. This program follows the standard multiplication algorithm.
1. Java program & output to Multiply Large numbers
Code has been copied
/*************************************** alphabetacoder.com Java program to multiply large numbers ****************************************/ import java.util.Scanner; class Main { public static void main(String args[]) { // declare instance of Scanner class Scanner sc = new Scanner(System.in); // declare varables char[] num1 = new char[500]; // for storing first numbers. char[] num2 = new char[500]; // for storing second numbers. int[] result = new int[1000]; // for storing the result int n1, n2, d1, d2, i, j, sum, carry, flag = 0; // Read input numbers System.out.print("Enter the first number: "); num1 = sc.next().toCharArray(); System.out.print("Enter the second number: "); num2 = sc.next().toCharArray(); //find the number of digits for both numbers. n1 = num1.length; n2 = num2.length; // Perform multiplication // Multiply each digit of num1 with each digit of num2 for (i = n1 - 1; i >= 0; i--) { // initialize carry = 0; d1 = num1[i] - '0'; // current digit of first number for (j = n2 - 1; j >= 0; j--) { d2 = num2[j] - '0'; // current digit of second number // calculate sum sum = d1 * d2 + result[i + j + 1] + carry; result[i + j + 1] = sum % 10; // calculate carry carry = sum / 10; } // Set the carry to the leading digit result[i] = carry; } // display the result // discard the leading 0s in result array System.out.print("Result = "); for (i = 0; i < (n1 + n2); i++) { if (result[i] != 0) flag = 1; if (flag == 1) System.out.print(result[i] + ""); } } }
Output
Enter the first number: 95645321827654784646846744467874574999555664226577
Enter the second number: 57454545445787798756998862211360065474755258565
Result = 5495258489623991547912527139389052273835545445473793418196901198146636507325023577503884379882005