所有能够整除x的数字。
我输入4,它返回:4、2、1。
编辑:我知道这听起来像作业。我正在编写一个小应用程序,用于使用半随机测试数据填充一些产品表。其中两个属性是ItemMaximum和Item Multiplier。我需要确保乘数不会创建一个不合逻辑的情况,即购买1个以上的物品将使订单超过允许的最大值。因此,这些因数将提供一个有效值列表,供我的测试数据使用。
编辑++:在得到大家的帮助后,我选择了以下内容。再次感谢!
编辑#:我编写了3个不同的版本,以查看哪个更好,并针对分解小数和非常大的数字进行了测试。我将粘贴结果。
static IEnumerable<int> GetFactors2(int n)
{
return from a in Enumerable.Range(1, n)
where n % a == 0
select a;
}
private IEnumerable<int> GetFactors3(int x)
{
for (int factor = 1; factor * factor <= x; factor++)
{
if (x % factor == 0)
{
yield return factor;
if (factor * factor != x)
yield return x / factor;
}
}
}
private IEnumerable<int> GetFactors1(int x)
{
int max = (int)Math.Ceiling(Math.Sqrt(x));
for (int factor = 1; factor < max; factor++)
{
if(x % factor == 0)
{
yield return factor;
if(factor != max)
yield return x / factor;
}
}
}
对于数字20,每个数字分解5次:
- GetFactors1-445,881
- GetFactors2-308,234
- GetFactors3-913,659
对于数字20000,每个数字分解5次:
- GetFactors1-5,644,457
- GetFactors2-12,117,938
- GetFactors3-3,108,182