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;
}
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With