def gcd(a,b): if bN: ans+=M/N M%=N else: ans+=1 M,N=N,M d=gcd(M,N) M/=d N/=d print ans+M-1