標籤:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace BigNumberMultiplication{ class Program { static void Main(string[] args) { try { int first = 4916; int second = 12345; long result = first * second; Console.WriteLine(string.Format("{0} * {1} = {2}\n\n", first.ToString(), second.ToString(), result.ToString())); string firstStr = "100000000000000000000"; string secondStr = "100000000000000000000"; string resultStr = MultipFunction(firstStr, secondStr); Console.WriteLine("The result is: {0}", resultStr.TrimStart(‘0‘)); Console.WriteLine("The length of the result is: {0}", resultStr.TrimStart(‘0‘).Length); Console.ReadKey(); } catch (Exception ex) { } } //大資料乘法 private static string MultipFunction(string firstNumStr, string secondNumStr) { try { int firstNumLength = firstNumStr.Length; int secondNumLength = secondNumStr.Length; int resultNumLength = firstNumLength + secondNumLength; int[] firstNumValue = new int[firstNumLength]; int[] secondNumValue = new int[secondNumLength]; int[] resultNumValue = new int[resultNumLength]; //遍曆字串,將每一位的字元轉換成為int整形插入整形數組中 for (int i = 0; i < firstNumLength; i++) { firstNumValue[i] = firstNumStr[i] - 48; } for (int i = 0; i < secondNumLength; i++) { secondNumValue[i] = secondNumStr[i] - 48; } //定義的整形數組初始化各個位就是0;所以下面賦0的過程可以省略 for(int i = 0; i < resultNumLength; i++) { resultNumValue[i] = 0; } //演算法的核心(小學筆算乘法的流程),將兩個數按位進行相乘-->組合成結果的整形數組 //然後對此結果整形數組進行遍曆,結果的低位取整附加給臨近的高位,低位取餘賦給本低位(註:這裡說的低位恰好是數組的高位,即數組下標大的位) for (int i = firstNumLength - 1; i >= 0; i--) { for (int j = secondNumLength - 1; j >= 0; j--) { resultNumValue[i + j + 1] += firstNumValue[i] * secondNumValue[j]; resultNumValue[i + j] += resultNumValue[i + j +1] /10; resultNumValue[i + j + 1] = resultNumValue[i + j + 1] % 10; } } //將整形數組轉化成字元數組 char[] temp = new char[resultNumLength]; for (int i = 0; i < resultNumLength; i++) { temp[i] = (char)(resultNumValue[i] + 48); } //將字元數組轉化為字串 string resultStr = new string(temp); return resultStr; } catch (Exception ex) { return string.Empty; } } }}
大資料相乘