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

前端 未结 12 1500
无人共我
无人共我 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:09
    • Find the first prime which divides the number N.
    • Let's say that prime is d.
    • Divide N by d.
    • This is the required result that you want.
    0 讨论(0)
  • 2020-12-29 12:14

    Optimization: An odd number can't have even number as largest divisor. Use this filter on number early. So if odd number is given.

    • First do division with 2.

    • Then decrement i by 2 everytime in loop

    This is will improve speed for odd numbers.

    0 讨论(0)
  • 2020-12-29 12:22

    Java implementation of the solution:

    static int highestDivisor(int n) {
        if ((n & 1) == 0)
            return n / 2;
        int i = 3;
        while (i * i <= n) {
            if (n % i == 0) {
                return n / i;
            }
            i = i + 2;
        }
        return 1;
    }
    
    0 讨论(0)
  • 2020-12-29 12:24

    Some additional optimizations:

    1.  If even then divisable by 2.
    2.  If the sum of the digits is divisable by 3, then number is divisble by 3 (ie 78 = 7 + 8 = 15 = 1 + 5 = 6 which is divisable by 3)
    3.  If it ends in 0 or 5 it is divisable by 5
    

    Gordon.

    0 讨论(0)
  • 2020-12-29 12:25

    You've basically hit the "factorization of large numbers" problem, which is the basis of today's Public Key encryption and is known (or hoped) to be a computationally hard problem. I indeed hope that you will not find a much better solution, otherwise the whole security infrastructure of the world will collapse... :)

    0 讨论(0)
  • 2020-12-29 12:25

    The best algorithm will depend on how huge your numbers will really be.

    This problem is basically as hard as factoring integers - if have some factoring algorithm, it will be rather easy to use it to construct the greatest non-trivial divisor. Again, which of all the known factoring algorithms you employ for a number should depend on its 'hugeness', as for different scales these fancy algorithms will likely have different performances.

    You will probably find several (maybe different) answers to your question in good books on cryptography, algorithmics and computational number theory.

    Again, depending on your scale, it might even be an option to simple precompute a large list a prime numbers, save it, and then given an input number search within this list for the smallest divisor - which will immediately have the greatest divisor pop up, too.

    0 讨论(0)
提交回复
热议问题