我正在研究一些 Project Euler 问题,需要一些帮助来理解我找到的解决方案。
我的问题是:在 SkipWhile 方法调用中到底在哪里设置了 X?当我在运行时中断代码并单步执行到那一点时,我从未看到为其设置值。然而,代码将一直有效。我检查了 SkipWhile 的定义,也许我只是不明白调用中传递的参数如何满足 3 参数方法定义。 Math.Pow 也一样 - X 在哪里设置!?
public long FindGreatestPrimeFactor(long factorGreaterThan, long number)
{
long upperBound = (long)Math.Ceiling(Math.Sqrt(number));
// find next factor of number
long nextFactor = Range(factorGreaterThan + 1, upperBound)
.SkipWhile(x => number % x > 0).FirstOrDefault();
// if no other factor was found, then the number must be prime
if (nextFactor == 0)
{
return number;
}
else
{
// find the multiplicity of the factor
long multiplicity = Enumerable.Range(1, Int32.MaxValue)
.TakeWhile(x => number % (long)Math.Pow(nextFactor, x) == 0)
.Last();
long quotient = number / (long)Math.Pow(nextFactor, multiplicity);
if (quotient == 1)
{
return nextFactor;
}
else
{
return FindGreatestPrimeFactor(nextFactor, quotient);
}
}
}
private IEnumerable<long> Range(long first, long last)
{
for (long i = first; i <= last; i++)
{
yield return i;
}
}
请您参考如下方法:
我相信你在谈论 lambda expression :
x => number % x > 0
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.
在 LINQ 表达式中,每个项目在迭代时都提供给 lambda。在 lambda 的主体中,如果你想引用该项目,你需要给它一个名字。在这种情况下,参数最终命名为 x。
