如何在循环时跳过循环中的索引

时间:2018-10-18 14:06:32

标签: c# performance loops

示例:我正在验证for循环中从1到1000的一些数字。

也许数字50是有效数字,所以可以跳过所有被50整除的数字(100、150、200、250等),因为它们也有效。

因此,我不需要再次验证这些数字来提高性能并将循环过程从1000个缩短到60个。

有办法吗?

因为您要求“验证”机制:

我想验证“友好”数字。这是“ Project Euler Problem 21”的一部分。我只是想改善自己的解决方案。

亲和的数字例如220和284,因为两个数字的适当除数之和就是它们自己的数字。

除数220:1、2、4、5、10、11、20、22、44、55和110 =>总和284

除数284:1、2、4、71和142 =>总和220

因此,两个数字都是“友好”数字。如果我要用284验证220,则无需再次检查284并可以跳过它。

List<int> ListOfAmicableNumbers = new List<int>();


for (int i = 1; i <= 1000; i++)
{
    if(IsAmicableNumber(i))
    {
        ListOfAmicableNumbers.Add(i);
    }
}

也许有一种聪明的数学方法可以跳过这些值。 因为遍历一个可能在100万次迭代中每次迭代变得越来越大的List可能会再次使其变慢。

1 个答案:

答案 0 :(得分:4)

int skipValue=50;
for(int i=1; i<=1000;i++)
{
   if(i%skipValue == 0) continue;
   //verification goes here...
}

编辑:由于您说可能需要多个skipValue,并且此skipValues列表逐渐增加,因此请尝试以下方式:

List<int> skipValues = new List<int>();//fill them somewhere else...
for(int i=1; i<=1000;i++)
{
   if(skipValues.Any(w => i%w == 0)) continue;
   //verification goes here...
   //after verification you may like to add this value into the list:
   skipValues.Add(i);
}
相关问题