Efficient algorithm for finding a common divisor closest to some value?

前端 未结 4 1042
终归单人心
终归单人心 2021-01-11 20:12

I have two numbers, x1 and x2. For a number y, I want to calculate the common divisor of x1 and x2 as close

4条回答
  •  我在风中等你
    2021-01-11 20:49

    1. Find the GCD of x1 and x2.
    2. If GCD <= Y then return GCD
    3. Current best answer is GCD, with a best distance of GCD - y.
    4. Iterate through all numbers Y +/- [0 ... best distance]
    5. Return the first integer that is a multiple of both x1 and x2

    To 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.

提交回复
热议问题