Getting Factors of a Number

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

    I got pretty good results with complexity of O(sqrt(N)).

    if (N == 1) return 1;
        int divisors = 0;
        int max = N;
        for (int div = 1; div < max; div++) {
            if (N % div == 0) {
                divisors++;
                if (div != N/div) {
                    divisors++;
                }
            }
            if (N/div < max) {
                max = N/div;
            }
        }
        return divisors;
    

提交回复
热议问题