Getting Factors of a Number

前端 未结 11 2043
误落风尘
误落风尘 2020-12-30 11:53

I\'m trying to refactor this algorithm to make it faster. What would be the first refactoring here for speed?

public int GetHowManyFactors(int numberToCheck         


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 12:36

    1. You can limit the upper limit of your FOR loop to numberToCheck / 2
    2. Start your loop counter at 2 (if your number is even) or 3 (for odd values). This should allow you to check every other number dropping your loop count by another 50%.

      public int GetHowManyFactors(int numberToCheck)
      {
        // we know 1 is a factor and the numberToCheck
        int factorCount = 2; 
      
        int i = 2 + ( numberToCheck % 2 ); //start at 2 (or 3 if numberToCheck is odd)
      
        for( ; i < numberToCheck / 2; i+=2) 
        {
           if (numberToCheck % i == 0)
              factorCount++;
        }
        return factorCount;
      }
      

提交回复
热议问题