from math import gcd M, N = map(int, input().split()) M //= gcd(M, N) N //= gcd(M, N) 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)