Recently, I began to review data structure and algorithms. Basicly I followed cuifenghui's steps. Yesterday I viewed his Big Integers Multiplication programs. Well, the idea is easy and great: use two char arrays to store two big numbers, then multiply them byte by byte. The following is my java version of his code.
1 import java.io.*;
2
3 public class Main {
4
5 public Main() {
6 }
7
8 public static void main(String [] args) {
9 String op1 = "", op2 = ""; // use String to store operators
10 char [] p1, p2, p; // use char array to compute
11
12 System.out.println("\nThis program compute multiplication of two big integers.\n\n" +
13 "Please input two big integers:");
14 try {
15 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16 op1 = br.readLine();
17 op2 = br.readLine();
18 } catch (IOException ioe) {
19 }
20
21 p1 = op1.toCharArray();
22 p2 = op2.toCharArray();
23 int length = p1.length + p2.length;
24 p = new char[length];
25 for (int i = 0; i < length; i ++) { // initial the result
26 p[i] = '0';
27 }
28
29 // the following is compute the result byte by byte
30 short carry = 0;
31 for (int i = p1.length - 1; i >= 0; i --) {
32 carry = 0;
33 for (int j = p2.length - 1; j >= 0; j --) {
34 carry += (p1[i] - '0') * (p2[j] - '0') + (p[i+j+1] - '0');
35 p[i+j+1] = (char)(carry % 10 + '0');
36 carry /= 10;
37 }
38 p[i] = (char)(carry + '0');
39 }
40
41 boolean printing = false;
42 System.out.println("\nThe result is:");
43 for (int i = 0; i < p.length; i ++) {
44 if (!printing && p[i] == '0') // trim beginning 0
45 continue;
46 System.out.print(p[i]);
47 printing = true;
48 }
49 System.out.println();
50 }
51
52 }
53
2
3 public class Main {
4
5 public Main() {
6 }
7
8 public static void main(String [] args) {
9 String op1 = "", op2 = ""; // use String to store operators
10 char [] p1, p2, p; // use char array to compute
11
12 System.out.println("\nThis program compute multiplication of two big integers.\n\n" +
13 "Please input two big integers:");
14 try {
15 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16 op1 = br.readLine();
17 op2 = br.readLine();
18 } catch (IOException ioe) {
19 }
20
21 p1 = op1.toCharArray();
22 p2 = op2.toCharArray();
23 int length = p1.length + p2.length;
24 p = new char[length];
25 for (int i = 0; i < length; i ++) { // initial the result
26 p[i] = '0';
27 }
28
29 // the following is compute the result byte by byte
30 short carry = 0;
31 for (int i = p1.length - 1; i >= 0; i --) {
32 carry = 0;
33 for (int j = p2.length - 1; j >= 0; j --) {
34 carry += (p1[i] - '0') * (p2[j] - '0') + (p[i+j+1] - '0');
35 p[i+j+1] = (char)(carry % 10 + '0');
36 carry /= 10;
37 }
38 p[i] = (char)(carry + '0');
39 }
40
41 boolean printing = false;
42 System.out.println("\nThe result is:");
43 for (int i = 0; i < p.length; i ++) {
44 if (!printing && p[i] == '0') // trim beginning 0
45 continue;
46 System.out.print(p[i]);
47 printing = true;
48 }
49 System.out.println();
50 }
51
52 }
53