I need an optimal algorithm to find the largest divisor of a number N. Preferably in C++ or C#

前端 未结 12 1498
无人共我
无人共我 2020-12-29 11:51

I am currently using the following code but its very slow for large numbers



        static int divisor(int number)
        {
            int i;
                    


        
12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 11:59

    A solution if you know the smallest divisor is to apply the following formula:

    largest_d = N - N % smallest_d
    

    where N is the number whose largest divisor you're looking for.

    def largest_divisor(N, smallest_divisor):
       return N - N % smallest_divisor
    

    This code with a random big number (N = 94e15) and a random big divisor (divisor = 21e3) finished running the program in Python in 0.000740051269531 s.

    Hope this helps.

提交回复
热议问题