I have two numbers, x1 and x2. For a number y, I want to calculate the common divisor of x1 and x2 as close
x1 and x2. GCD <= Y then return GCDGCD, with a best distance of GCD - y.x1 and x2To find the GCD
public int getGCD( int a, int b )
{
return (b==0) ? a : gcd(b, a%b);
}
To find closest divisor to y...
public int closestDivisor( int a, int b, int y ){
int gcd = getGCD( a, b );
if( gcd <= y ) return gcd;
int best = gcd - y;
for( int i = 0; i < best; i++ )
{
if( gcd % (i-y) == 0 ) return i - y;
if( gcd % (i+y) == 0 ) return i + y;
}
return gcd;
}
I believe the only additional optimization available would be to factor the gcd (perhaps using a sieve?) as @trinithis suggested.