/* 分からない */ package no187; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.NoSuchElementException; public class Main { static long MOD = 1000000007; static IO io = new IO(); public static void main(String[] args) { int n = io.nextInt(); long[] a = new long[n]; long[] b = new long[n]; long[] m = new long[n]; for(int i=0;i<3;i++) { a[i] = 1; b[i] = io.nextLong(); m[i] = io.nextLong(); } long[] x = Mod.linearCongruence(a, b, m, MOD); if (x == null) { System.out.println(-1); }else if(x[0] == 0) { System.out.println(x[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 mod) { long x = 0; long m = 1; for(int i=0;i Integer.MAX_VALUE) { throw new NumberFormatException(); } return (int) nl; } public char nextChar() { if (!hasNext()) { throw new NoSuchElementException(); } return (char) readByte(); } public double nextDouble() { return Double.parseDouble(next());} public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i=0;i