I need an optimal algorithm to find the largest divisor of a number N. Preferably in C++ or C#
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.
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;
}
In order to limit your search space, you should start at 2 and work up to the square root of the number. There are far more numbers (in a finite search space) divisible by 2 than by 27 so you're more likely to get a low divisor than a high one, statistically speaking.
You'll find a big difference when using the square root, rather than half the value, when you processing (for example) 1,000,000. The difference is between a search space of 500,000 for your method and 1,000 for the square root method is considerable.
Another advantage is to halve the search space right at the front by discounting multiples of two. Then, when you have your lowest divisor, the highest one is simply the number divided by that.
Pseudocode:
if n % 2 == 0: # Halve search space straight up.
print n / 2
else:
i = 3 # Start at 3.
while i * i <= n: # Or use i <= sqrt(n), provided sqrt is calc'ed once
if n % i == 0:
print n / i # If multiple, get opposite number, print and stop
break
i = i + 2 # Only need to process odd numbers