我有一个数字的质因子列表,格式如下: int[] factor = {number of factors,factor1,poweroffactor1,factor2,poweroffactor2,...};
我想获得等效的动态嵌套 for 循环,它将产生所有因素,其中 for 循环看起来像这样:
int currentpod = 1;
for(int i=0;i<factors[2];i++)
{
currentprod *= Math.Pow(factors[1],i);
for(int j=0;j<factors[4];j++)
{
currentprod *= Math.Pow(factors[3],i);
...
//When it hits the last level (i.e. the last prime in the list, it writes it to a list of divisors
for(int k=0;k<factors[6];k++)
{
divisors.Add(Math.Pow(factors[5],k)*currentprod);
}
}
}
不幸的是,由于 currentprod 没有得到足够的重置,这段代码就崩溃了。这是我用来尝试完成此操作的实际代码:
public static List<int> createdivisorlist(int level, List<int> factors, int[] prodsofar,List<int> listsofar)
{
if (level == factors[0])
{
prodsofar[0] = 1;
}
if (level > 1)
{
for (int i = 0; i <= 2*(factors[0]-level)+1; i++)
{
prodsofar[level-1] = prodsofar[level] * (int)Math.Pow(factors[2 * (factors[0] - level) + 1], i);
listsofar = createdivisorlist(level - 1, factors, prodsofar, listsofar);
}
}
else
{
for (int i = 0; i <= factors.Last(); i++)
{
listsofar.Add(prodsofar[level] * (int)Math.Pow(factors[2 * (factors[0] - level) + 1], i));
if (listsofar.Last() < 0)
{
int p = 0;
}
}
return listsofar;
}
return listsofar;
}
原始参数是: level = Factors[0] Factors = 上面指定格式的素因子列表 prodsofar[] = 所有元素都是 1 个 listsofar = 一个空列表
我如何重置 prodsofar 以使其不会“爆炸”而只是按照我的概述进行操作?注意:作为测试,使用2310,在当前代码下,要添加的除数为负(int溢出)。