Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

algorithm

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



        static int divisor(int number)
        {
            int i;
            for (i = number / 2; i >= 1; i--)
            {
                if (number % i == 0)
                {
                    break;
                }
            }
            return i;
        }
like image 975
Ronzii Avatar asked Aug 23 '10 06:08

Ronzii


1 Answers

Don't know if it's the optimal solution but you'd probably be better starting at 2 then going upwards such as:

  static int divisor(int number)
    {
        int i;
        for (i = 2; i <sqrt(number); i++)
        {
            if (number % i == 0)
            {
                break;
            }
        }
        return number/i;
    }

EDIT

to get it to work with primes as well:

 static int divisor(int number)
    {
        int i;
        for (i = 2; i <=sqrt(number); i++)
        {
            if (number % i == 0)
            {
                return number/i;
            }
        }
        return 1;
    }
like image 125
Scott Logan Avatar answered Oct 06 '22 00:10

Scott Logan