g(a,b){return b?g(b,a%b):a;} c;main(a,b){for(scanf("%d%d",&a,&b),a/=g(a,b),b/=g(a,b);a-1&&b-1;a^=b^=a^=b)c+=a/b+1,a-=a/b*b;printf("%d",a+b+c-2);}