Find X such that X is the largest divisor of Y that is less than or equal to M.

50 Views Asked by At

I have this function that finds X such that X is the largest divisor of Y that is less than or equal to M (and X != 1). in other words, Y/X gives least amount of remainders when dividing from 2 to M.

I was wondering if this can be reduced to some mathematical formula?

int Dividend = 55;
int LargestDivisor = 8;

int BestDivisor = LargestDivisor;
int BestRemainder = Dividend % BestDivisor;

int Divisor = BestDivisor - 1;
while (Divisor > 1)
{
    int Remainder = Dividend % Divisor;
    if (Remainder < BestRemainder)
    {
        BestDivisor = Divisor;
        BestRemainder = Remainder;
    }
    Divisor--;
}
int Result = BestDivisor;