f=->x,y{return[x,1,0]if y==0 g,a,b=f[y,x%y] [g,b,a-x/y*b]} gets a=$<.map{|e|e.split.map &:to_i} p (r=a.reduce{|(a,m),(b,n)|g,x,y=f[m,n] break if(b-=a)/g*g