What's New in .net 4.0- 基础类库

xiaoxiao2026-08-21  20

1. System.Numerics.BigInteger 在C# 4.0的基础类库中,终于有了大数BigInteger,这个大数与其他.net的数值类型不同,它没有最大值和最小值的限制,理论上它可以存无限大的数(取决于你的程序的寻址空间),它与我以前使用的F#的Microsoft.FSharp.Math.BigInt的方法基本一致,但更方便,它可以自动从小数造型成大数,而不需要一再呼叫FromInt32...等等系列方法。BigInteger还提供了很好的构造器,除了接受小数的参数外,还可以接受Byte[]阵列作为参数(在没有大数之前,很多程序就利用byte[]来保存大数),并依照下标顺序构造出一个大数。如 [code] Byte array (lowest index first) 00 10 A5 D4 E8 00 将构造出 Hexadecimal string E8D4A51000 [/code] 其他运算方法与别的数值类型类似,请看代码 [code] using System; using System.Numerics; using System.Threading; namespace LucasLehmer { class Program { static void Main(string[] args) { int range = 1000; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); Parallel.For(2, range, delegate(int i) { if (LucasLehmerTest(i)) { System.Console.WriteLine("M({0})={1}", i, Mersenne(i)); } }); sw.Stop(); System.Console.WriteLine("It take {0} seconds to caculate Mersenne in {1}", sw.ElapsedMilliseconds/1000, range); } public static BigInteger tcs(BigInteger n, BigInteger m, BigInteger result) { if(n.IsZero){ return result; } return tcs((n - BigInteger.One), m, ((BigInteger.Pow(result, 2) - 2 ) % m)); } public static BigInteger seq(BigInteger n, BigInteger m) { return tcs(n, m, 4 % m); } public static BigInteger LucasLehmerSequence(BigInteger n, BigInteger m) { if (n==BigInteger.Zero) return 4% m; return (BigInteger.Pow(LucasLehmerSequence(n - BigInteger.One, m), 2) - 2) % m; } public static BigInteger Mersenne(int n) { return BigInteger.Pow(2,n)-BigInteger.One; } public static bool LucasLehmerTest(int n){ BigInteger m = Mersenne(n); return (seq(n - 2, m).IsZero); //return (LucasLehmerSequence(BigInt.FromInt32(n - 2), m) == BigInt.Zero); } } } [/code]
转载请注明原文地址: https://www.6miu.com/read-5051578.html

最新回复(0)