Getting Factors of a Number

前端 未结 11 1933
误落风尘
误落风尘 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;
        }
    
    0 讨论(0)
  • 2020-12-30 12:35

    Reducing the bound of how high you have to go as you could knowingly stop at the square root of the number, though this does carry the caution of picking out squares that would have the odd number of factors, but it does help reduce how often the loop has to be executed.

    0 讨论(0)
  • 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;
      }
      
    0 讨论(0)
  • 2020-12-30 12:38

    An easy to implement algorithm that will bring you much farther than trial division is Pollard Rho

    Here is a Java implementation, that should be easy to adapt to C#: http://www.cs.princeton.edu/introcs/78crypto/PollardRho.java.html

    0 讨论(0)
  • 2020-12-30 12:40

    Python Implementation Score 100% https://app.codility.com/demo/results/trainingJ78AK2-DZ5/

    
    import math;
    
    def solution(N):
        # write your code in Python 3.6
        NumberFactor=2; #one and the number itself
        if(N==1):
            return 1;
        if(N==2):
            return 2;
        squareN=int(math.sqrt(N)) +1;
        #print(squareN)
    
        for elem in range (2,squareN):
            if(N%elem==0):
                NumberFactor+=2;
        
        if( (squareN-1) * (squareN-1) ==N):
            NumberFactor-=1;
        return NumberFactor
    
    0 讨论(0)
提交回复
热议问题