I am currently using the following code but its very slow for large numbers
static int divisor(int number)
{
int i;
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.
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;
}
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.
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... :)
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.