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

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

    I think you can do it by greedy algorithm, first find GCD by common algorithms name it d (which is computable in logarithmic time) then find factors of d each time divide d to smallest available factor (create d'), and compare |d'-y| with |d-y| if is smaller continue in this way (and replace d' with d), else, multiply d' with smallest eliminated factor, and again compare its distance to y.

提交回复
热议问题