mod = 998244353 eps = 10**-9 def main(): import sys input = sys.stdin.readline def matmul(A, B): C = [[0] * len(B[0]) for _ in range(len(A))] for i in range(len(A)): for k in range(len(B)): for j in range(len(B[0])): C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod return C def matpow(A, p): n = len(A) B = [[0] * n for _ in range(n)] for i in range(n): B[i][i] = 1 while p > 0: if p & 1: B = matmul(B, A) A = matmul(A, A) p >>= 1 return B # x**k == y % mod # O(mod**0.5) def DiscreteLog(x, y, mod): m = int(mod ** 0.5) + 1 dic = {1: 0} # baby-step xi = 1 for i in range(1, m + 1): xi = (xi * x) % mod dic[xi] = i if y in dic: return dic[y] # giant-step r = pow(xi, mod - 2, mod) for a in range(1, m + 1): y = (y * r) % mod if y in dic: return a * m + dic[y] return -1 A, B, P, Q = map(int, input().split()) if B == 0: ans = DiscreteLog(A, P, mod) if 2 <= ans <= 10 ** 18: print(ans) else: print(ans + mod - 1) exit() if (A * A - 2 * B)%mod == P and A == Q: print(2) exit() M = [[A, -B], [1, 0]] B_inv = pow(B, mod-2, mod) M_inv = [[0, 1], [(-B_inv)%mod, (A * B_inv)%mod]] M_pow = {} M_cur = [[1, 0], [0, 1]] initial_vec = [[A], [2]] for i in range(1, 10 ** 5 + 1): M_cur = matmul(M_cur, M) U = matmul(M_cur, initial_vec) if U[0][0] == P and U[1][0] == Q: print(i + 1) exit() U_hash = U[0][0] * mod + U[1][0] M_pow[U_hash] = i M_inv_p = matpow(M_inv, 10 ** 5) M_inv_cur = [[1, 0], [0, 1]] last_vec = [[P], [Q]] for i in range(1, 10 ** 5 + 1): M_inv_cur = matmul(M_inv_cur, M_inv_p) V = matmul(M_inv_cur, last_vec) V_hash = V[0][0] * mod + V[1][0] if V_hash in M_pow: j = M_pow[V_hash] print(i * (10 ** 5) + j + 1) exit() if __name__ == '__main__': main()