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