package no186; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long[] a = new long[3]; long[] b = new long[3]; long[] m = new long[3]; for(int i=0;i<3;i++) { int x = sc.nextInt(); int y = sc.nextInt(); a[i] = 1; b[i] = x; m[i] = y; } long[] x = Mod.linearCongruence(a, b, m); if (x == null) { System.out.println(-1); }else if(x[0] == 0) { if (x[1] > 0) { System.out.println(x[1]); }else{ System.out.println(-1); } }else{ System.out.println((x[0]%x[1]+x[1])%x[1]); } } } class Mod { public static long inverse(long a,long mod) { long b = mod, u = 1, v = 0; while(b > 0) { long temp; long t = a / b; a -= t * b; temp = a; a = b; b = temp; u -= t * v; temp = u; u = v; v = temp; } return (u % mod + mod) % mod; } public static long[] linearCongruence(long[] A,long[] B,long[] M) { long x = 0; long m = 1; for(int i=0;i