【发布时间】:2019-07-25 10:14:07
【问题描述】:
所以我正在开发一个程序来分解给定的数字。您在命令行中编写一个数字,它会为您提供所有因素。现在,按顺序执行此操作非常慢。因为它只使用一个线程,如果我没记错的话。现在,我想用Parallel.For 来做这件事,它只对整数有效,所以想用 BigIntegers 试试
这里是正常代码:
public static void Factor(BigInteger f)
{
for(BigInteger i = 1; i <= f; i++)
{
if (f % i == 0)
{
Console.WriteLine("{0} is a factor of {1}", i, f);
}
}
}
上面的代码应该很容易理解。但正如我所说,这对于大数字来说非常慢(超过 10 亿它开始变得不切实际),这是我的并行代码:
public static void ParallelFacotr(BigInteger d)
{
Parallel.For<BigInteger>(0, d, new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, i =>
{
try
{
if (d % i == 0)
{
Console.WriteLine("{0} is a factor of {1}", i, d);
}
}
catch (DivideByZeroException)
{
Console.WriteLine("Done!");
Console.ReadKey();
Launcher.Main();
}
});
}
现在,上面的代码(并行代码)可以很好地处理整数(int),但速度非常快。它在 2 秒内分解了 1000.000.000。所以我想为什么不尝试使用更大的整数。而且,我认为将<Biginteger> 放在parallel.for 之后就可以了。但事实并非如此。那么,您如何在 for 循环中并行处理 bigintegers 呢?我已经尝试了一个以 bigInteger 作为参数的常规并行循环,但是它给出了一个错误,说它不能从 BigInteger 转换为 int。那你呢
【问题讨论】:
标签: c#