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

前端 未结 12 1570
无人共我
无人共我 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 12:04

    First thought you can find the smallest divisor d (not equal to 1 of course), then N/d will be the largest divisor you're looking for.

    For example if N is divisible by 3 then you'll need 2 iterations to find the answer - in your case it would be about N/6 iterations.

    Edit: To further improve your algorithm you can iterate through odd numbers only (after checking if you number is even) or, even better, if you have the list of primes pre-calculated then you can iterate through them only because smallest divisor is obviously is a prime number.

提交回复
热议问题