首先,将乘数和被乘数按照每三位进行划分,列出乘法表,乘数和被乘数的地位分别放在表格的右端和上端。
8 216 547
96 785
计算表格中的数值
8
216
547
*
768
20736
52512
96
6250
169560
429395
785
向右错位后按列相加
768
20736
52512
6250
169560
429395
768
27016
222072
429395
最后一行,从个位数开始,以1000进制进行进位,超出1000的部分进位到前一个方格里:
768
27016
222072
429395
768+27=795
27016+222=27238
222072+429=222501
留395进429
795
238
501
395
最后一排的最前端的方格可以不用再往前进位,所以8216547*96785 = 795238501395
import java.awt.List; import java.util.Scanner; /** * * @author yyc 大整数乘法:采用“表格法” */ public class Main { public static void main(String[] args) { // TODO Auto-generated method stub // 输入乘数与被乘数 Scanner scanner = new Scanner(System.in); String mulStrA = scanner.nextLine(); String mulStrB = scanner.nextLine(); // 求得乘积 String resultStr = BigIntegerMul(mulStrA, mulStrB); System.out.println(resultStr); } public static String BigIntegerMul(String mulStrA, String mulStrB) { int[] mListA = SplitToArray(mulStrA); int[] mListB = SplitToArray(mulStrB); int[][] mulArray = new int[mListA.length][mListB.length]; // 计算表格 for (int i = 0; i < mListA.length; i++) { for (int j = 0; j < mListB.length; j++) { mulArray[i][j] = mListA[i] * mListB[j]; } } // 错位累加 int[] reArray = new int[mListA.length + mListB.length + 1]; int lastEffectIndex = 0; for (int n = 0; n < reArray.length; n++) { int iniRe = 0; for (int j = n; j >= 0; j--) { int i = n - j; if ((j < mListB.length) && (i < mListA.length)) { iniRe += mulArray[i][j]; lastEffectIndex = n; } } reArray[n] = iniRe; } // 进位操作 for (int i = lastEffectIndex; i > 0; i--) { reArray[i - 1] += reArray[i] / 1000; reArray[i] = reArray[i] % 1000; } // 拼接结果 StringBuffer sBuffer = new StringBuffer(); for (int i = 0; i <= lastEffectIndex; i++) { String string = ((Integer) reArray[i]).toString(); for (int j = 0; j < 3 - string.length(); j++) { sBuffer.append("0"); } sBuffer.append(string); } return sBuffer.toString(); } public static int[] SplitToArray(String mulStr) { // 将乘数与被乘数从各位开始,每三位划分,放入数据 int len = (int) Math.ceil(((double) mulStr.length()) / 3); int[] mList = new int[len]; int i = mulStr.length() - 1; int n = len - 1; while (i >= 0) { StringBuffer sb = new StringBuffer(); int interval = 3; if (i < 2) { interval = i + 1; } for (int j = interval - 1; j >= 0; j--) { sb.append(mulStr.charAt(i - j)); } mList[n] = Integer.parseInt(sb.toString()); n--; i -= interval; } return mList; } }