作为我的BigDecimal库的一部分,我需要计算任何给定的非负整数的阶乘。因此,我使用 .Net 4.0 的 System.Numerics.BigInteger
来存储巨大的数字。这是我正在使用的函数:
private BigInteger Factorial(BigInteger x)
{
BigInteger res = x;
x--;
while (x > 1)
{
res *= x;
x--;
}
return res;
}
它可以工作,但不够优化。现在我想使用并行计算,所以这是我尝试过的内容:(我没有并行编程的经验)
public BigInteger Factorial(long x)
{
BigInteger res = 1;
ParallelLoopResult r = Parallel.For(2L, (x + 1), i =>
res *= i
);
return res;
}
奇怪的问题是,上述函数对于像5!这样的小数字完美地工作,但对于像1000!这样的大数字却不起作用,并且每次返回完全不同的结果。因此,我意识到它不是线程安全的,问题出在变量res
上。我想知道正确的实现是什么?
如果我可以使用BigInteger代替变量x
,那就更好了。
Environment.ProcessorCount
作为DegreeOfParallelism。 - Jeroen van Langenfor
循环中出现了一个偏移量错误(应该是i <= upperBound
而不是i < upperBound
)。我已经修复了它。 - Cristian Lupascu