Getting Factors of a Number

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

    Well if you are going to use this function a lot you can use modified algorithm of Eratosthenes http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes and store answars for a interval 1 to Max in array. It will run IntializeArray() once and after it will return answers in 0(1).

    const int Max =1000000;
    int arr [] = new int [Max+1];
    
    public void InitializeArray()
    {
        for(int i=1;i<=Max;++i)
            arr[i]=1;//1 is factor for everyone
    
        for(int i=2;i<=Max;++i)
            for(int j=i;i<=Max;i+=j)
               ++arr[j];
    }
    public int GetHowManyFactors(int numberToCheck)
    {
       return arr[numberToCheck];
    }
    

    But if you are not going to use this function a lot I think best solution is to check unitll square root.


    Note: I have corrected my code!

提交回复
热议问题