from math import gcd M, N = map(int, input().split()) g = gcd(M, N) M //= g N //= g ans = 0 if M < N: ans += 1 M, N = N, M while True: if N == 1: ans += M - 1 break ans += M // N + 1 M, N = N, M % N if N == 0: print(-1) exit() print(ans)