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

前端 未结 4 1006
终归单人心
终归单人心 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:57

    This is efficient as I can get it:

    from fractions import gcd
    primes=[i for i in range(2,1000) if all(i%j!=0 for j in range(2,i))] #ensure you have enough primes.. (can improve efficency here)
    
    
    def f(x1,x2,y):
        _gcd=gcd(x1,x2)
        if _gcd==1:
            return 1
        factors=(i for i in range(2,_gcd+1) if _gcd%i==0) #can improve efficiency here.. e.g. only go up to root(gcd)
        r1=999999999
        r2=999999999
        for i in factors:
            r1=min(r1,y%i)
            r2=min(r2,i-y%i)
        return y-r1 if r1<=r2 else y+r2
    
    
    print f(8,4,3)
    print f(16,12,5)
    print f(997,53,44)
    print f(2300*2,2300*3,57)
    
    """
    2
    4
    1
    56
    """
    

提交回复
热议问题