C#中關於處理兩個大數相乘的問題


方法一:直接利用.NET FrameWork 4.0中自帶的System.Numeric類庫

 

添加了對此類庫的引用后,直接調用方法即可計算:

View Code
1 BigInteger num1 = BigInteger.Parse("乘數一");
2 BigInteger num2 = BigInteger.Parse("乘數二");
3 Console.WriteLine(num1* num2);
4 Console.ReadKey();

 

方法二:自己手寫一個計算的方法

思路:因為兩個大數相乘,結果可能已經超過了C#定義的變量的范圍,所以我們應該使用字符串代替的處理想法,將數字相乘轉化為字符串的處理!具體代碼如下:

View Code
 1             static string getbackresult(string s1, string s2)
2 {
3 string lastResult = "";
4 int ten1 = -1;
5 int[] result = new int[s1.Length + s2.Length];//用以記錄計算結果
6 for (int i = s1.Length - 1; i >=0; i--)
7 {
8 int c1 = Convert.ToInt16(s1[i].ToString());//從s1中從后往a前取一個數並記錄這個數的位置
9 ten1++;
10 int resultindex = result.Length - 1 - ten1;
11 for (int j = s2.Length - 1; j >=0; j--)
12 {
13 int c2 = Convert.ToInt16(s2[j].ToString());//從?s2中從后往前取一個數
14 int cc = c1 * c2 + result[resultindex];
15 if (cc > 10)
16 {
17 result[resultindex] = cc % 10;
18 int lastindex = resultindex - 1; //往前移動一位
19 int lastvalue = result[lastindex] + cc / 10; //把剛剛得到的十位的數字賦值到前面
20 while (cc > 10)
21 {
22 cc = result[lastindex] + cc / 10;
23 result[lastindex] = cc % 10;
24 lastindex--;//進位
25 }
26 }
27 else
28 {
29 result[resultindex] = cc;
30 }
31 resultindex--;//進位
32 }
33 }
34 StringBuilder sb = new StringBuilder();
35 foreach (int item in result)
36 {
37 sb.Append(item);
38 }
39 lastResult = sb.ToString();
40 if (lastResult[0]=='0')
41 {
42 lastResult = lastResult.Substring(1);
43 }
44 return lastResult;
45 }





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM