【发布时间】:2013-10-25 02:52:11
【问题描述】:
我有一个数字的质因数列表,格式如下: int[] 因子 = {因子数,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;
}
原来的论点是: 水平=因素[0] 因子 = 上面指定格式的主要因子列表 prodsofar[] = 所有元素都是 1 listofar = 一个空列表
如何重置 prodsofar 以使其不会“爆炸”而只是按照我的概述进行操作? 注意:作为测试,使用2310,在当前代码下,要添加的除数为负(int溢出)。
【问题讨论】:
-
这看起来不必要地复杂。
prodsofar和listsofar应该代表什么? -
当前乘积(要传递给函数的下一个实例以便它可以相乘),listofar 是除数列表。
-
我知道 c++,但不知道 c#。即便如此,我还是看到了一些看起来像错误的东西。循环限制看起来不对,
prodsofar可以是int,而不是int[],您可以使用*=并取消Pow。在尝试 2310 之前,您是否尝试过在 2 上运行它?
标签: c# math recursion prime-factoring