.Net中大数加减乘除运算

在.Net 4.0中,有封装了大数运算的方法,效率超级快。

 

  BigInteger a = BigInteger.Parse("124548787123123123335723122");
BigInteger b = BigInteger.Parse("7852132487452222222222222221440231333");
txtmsg.Text += "b/a=" + BigInteger.Divide(b, a).ToString() + "\r\n";
txtmsg.Text += "b+a=" + BigInteger.Add(b, a).ToString() + "\r\n";
txtmsg.Text += "b-a=" + BigInteger.Subtract(b, a).ToString() + "\r\n";
txtmsg.Text += "b*a=" + BigInteger.Multiply(b, a).ToString() + "\r\n";
txtmsg.Text += "b%a=" + BigInteger.Remainder(b, a).ToString() + "\r\n";


需要添加引用:

using System.Numerics;

 

用大数乘法做了一个实验:

计算1000以内的所有素数的乘积:

自己用乘法的步骤实现,取一个大数的每一位跟第二个大数相乘,得到的结果相加,结果跟官方的速度相比慢了100多倍。

int n=1000;
int[] nums = GetAllKNum(n);

//自己的土方法
methodone one = new methodone();
Stopwatch wc1 = new Stopwatch();
wc1.Start();
string result1 = one.P(n, nums);
wc1.Stop();
long long1= wc1.ElapsedMilliseconds;

//.net4.0的方法
methodtwo two = new methodtwo();
wc1.Reset();
wc1.Start();
string result2 = two.P(n, nums);
wc1.Stop();
long long2 = wc1.ElapsedMilliseconds;

//显示结果
txtmsg.Text = "";
txtmsg.Text += "自己的土方法:\r\n";
txtmsg.Text += "结果:" + result1 + "\r\n";
txtmsg.Text += "耗时:" + long1.ToString() + "毫秒\r\n\r\n";
txtmsg.Text += ".net4.0的方法:\r\n";
txtmsg.Text += "结果:" + result2 + "\r\n";
txtmsg.Text += "耗时:" + long2.ToString() + "毫秒\r\n";


结果截图:

实在惭愧,自己的土方法比官方的慢了100多倍,不知道官方是如何实现的。

posted @ 2012-01-08 21:44  小y  阅读(2104)  评论(0编辑  收藏  举报