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 }




posted @ 2012-04-02 11:12  秋恨雪  阅读(3161)  评论(2编辑  收藏  举报