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

前端 未结 12 1546
无人共我
无人共我 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条回答
  •  旧时难觅i
    2020-12-29 12:05

    A huge optimization (not sure if it's completely optimal - you'd have to ask a mathematician for that) is to search upwards using only prime numbers. As Vladimir and Bunnit said, it is better to search upwards, because you'll find it to be much faster. Then, return the inverse (number / i). However, if you've already tried 2 and come up dry, there is no point in trying 4 or 6. Similarly, if you've tried 3, there's no point in trying 6 or 9.

    So, if time of running is a big concern, you could have a list of the first 100 primes hard coded in your program. Test each of them. If you don't find an answer by then, then you could just increment by 2 (skipping even numbers).

提交回复
热议问题