import sys, itertools sys.setrecursionlimit(500005) stdin = sys.stdin ni = lambda: int(ns()) na = lambda: list(map(int, stdin.readline().split())) ns = lambda: stdin.readline().strip() a, b, n, m = na() def con(a, b, n): if (a - b) % n == 0: return (a - b) // n -1 else: return (a - b) // n if a < b: c = con(b, a, m) a += c + 1 b -= m * (c + 1) ans = a - 1 c = con(a, b, n) if c != 0: d = a - (n * (c + 1)) a = b + c else: d = 0 a = 0 elif a > b: c = con(a, b, n) a -= n * (c + 1) b += c + 1 ans = b - 1 c = con(b, a, m) if c != 0: b = a + c d = b - (m * (c + 1)) else: b = 0 d = 0 print(max(a, b, ans, d))