当前位置: 首页 > 编程语言 > C#

C#中的MillerRabin素数测试分享

时间:2023-04-11 12:02:02 C#

C#中的MillerRabin素数测试欢迎。我正在尝试实施MillerRabin测试以检查给定的大数量是否为质数。这是我的代码:publicstaticboolMillerRabinTest(BigIntegernumber){BigIntegerd;varn=数字-1;vars=FindK(n,d);大整数a=2;BigIntegery=Calc(a,d,number);//a^d模数if(y!=BigInteger.One&&y!=n){for(varr=1;r<=s-1;r++){y=Calc(y,2,number);如果(y==1)返回假;}如果(y!=n)返回false;}返回真;//它可能是素数}它适用于小的双整数。但是,如果我的程序需要评估包含超过16位数字的数字,程序就会冻结。例如,在成功检查一个数是否为质数后,程序突然变得没有响应。我不明白这怎么可能。如果检查了一个皇后,再检查另一个应该没问题。甚至调试器也无济于事,因为步骤选项已经消失。如果需要,我可以分享更多功能代码。上面的函数适用于小数字。编辑。更改BigInteger.ModPow的模函数会有所帮助。不幸的是,现在对于更大的数字,超过3000位,它永远不会返回素数,这是不可能的。还是很难找到真正的prme数字?好吧,我的工作站(Corei53.2GHz,IA64.Net4.5)需要大约5秒来测试一个数字是否等于2**3000个素数:publicstaticclassPrimeExtensions{//随机生成器(线程安全)privatestaticThreadLocals_Gen=newThreadLocal(()=>{returnnewRandom();});//随机生成器(线程安全)privatestaticRandomGen{get{returns_Gen.Value;}}publicstaticBooleanIsProbablyPrime(thisBigIntegervalue,intwitnesses=10){if(value=value-2);BigIntegerx=BigInteger.ModPow(a,d,value);如果(x==1||x==值-1)继续;for(intr=1;rtestsandbenchmarksBigIntegervalue=BigInteger.Pow(2,3217)-1;//梅森素数(2.5e968)Stopwatchsw=newStopwatch();sw.Start();BooleanisPrime=value.IsProbablyPrime(10);sw.Stop();Console.Write(isPrime?"probablyprime":"notprime");Console.WriteLine();Console.Write(sw.ElapsedMilliseconds);这是我的代码,您可以检查从0到十进制的质数。MaxValue=79228162514264337593543950335更新我做了一些调整以使程序更快:英特尔(R)Atom(TM)@1.60GHz2.00GBRAM32-bitOSResults:1.UInt32.MaxValue=4294967295ThelargestprimenumberbelowUInt32.MaxValueis4294967291Elapsedtimeis0.015600seconds2.ulong.MaxValue=UInt64.MaxValue=18446744073709551615ulong下面的最大素数.MaxValue是18446744073709551533经过的时间是3分钟和57.6059176秒3.decimal.MaxValue=79228162514264337593543950335十进制以下的最大数字.MaxValue测试的是79228162514264337593543950319,但不知道79228162514264337593543950319是素数,因为我在经过Therunningoftheprogramwasinterruptedafter3hoursand40minutes(needtouseahigh-speclaptopfortesting)TheaboveisthewholecontentsharedbytheC#learningtutorial:MillerRabinprimalitytestinC#,ifitisusefultoeveryoneandneedstoknowmoreMoreaboutC#learningtutorials,Ihopeeveryonewillpaymoreattention—usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacePrimalityTest{classProgram{staticvoidMain(string[]args){Console.Write("Enteranumber:");decimaldecimal_number=Convert.ToDecimal(Console.ReadLine());DateTimedate=DateTime.Now;ulongulong_a;ulongulong_b;if(decimal_number本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:

最新推荐
猜你喜欢