Getting Factors of a Number

前端 未结 11 2034
误落风尘
误落风尘 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:34

    https://codility.com/demo/results/demoAAW2WH-MGF/

     public int solution(int n) {
          var counter = 0;          
          if (n == 1) return 1;
          counter = 2; //1 and itself      
          int sqrtPoint = (Int32)(Math.Truncate(Math.Sqrt(n)));
          for (int i = 2; i <= sqrtPoint; i++)
          {
            if (n % i == 0)
            {
              counter += 2; //  We found a pair of factors.         
            }       
          }
          // Check if our number is an exact square.
          if (sqrtPoint * sqrtPoint == n)
          {
            counter -=1;
          }
    
          return counter;
        }
    

提交回复
热议问题