using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;

namespace ConsoleApplication1.CodeForces
{
    class _403
    {
        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), Encoding.ASCII, 1024 * 10);

        static void Main(String[] args)
        {
            var line = reader.ReadLine().Split(' ').Select(int.Parse).ToList();
            var a = line[0];
            var b = line[1];
            line = reader.ReadLine().Split(' ').Select(int.Parse).ToList();
            var c = line[0];
            var d = line[1];

            for(var i = 0; i < 100000; i++)
            {
                var dem = a * i + b - d;
                if(dem % c == 0 && dem >= 0)
                {
                        Console.WriteLine(b + (i) * a);
                        return;
                }
            }

            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Problem787A
{
    class Program
    {
        static int UCLN(int a, int b)
        {
            int r = a % b;
            if (r != 0)
                return UCLN(b, r);
            else
                return b;
        }
        static void Main(string[] args)
        {
            int a = NextInt(), b = NextInt();
            int c = NextInt(), d = NextInt();
            int flag = 0;
            if (a > c)
                flag = UCLN(a, c);
            else
                flag = UCLN(c, a);
            if ((d - b) % flag != 0)
                Console.Write(-1);
            else
            {
                int x = b;
                int y = d;
                while (x != y)
                {
                    if (x < y)
                        x += a;
                    else
                        y += c;
                }
                Console.Write(x);
            }
            Console.ReadLine();
        }
        static int s_index = 0;
        static List<string> s_tokens;
        private static string Next()
        {
            while (s_tokens == null || s_index == s_tokens.Count)
            {
                s_tokens = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                s_index = 0;
            }
            return s_tokens[s_index++];
        }
        private static int NextInt()
        {
            return Int32.Parse(Next());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleTraining
{
  public class Program
  {
    static void Main(string[] args)
    {
      List<int> sd = Console.ReadLine().Split().Select(int.Parse).ToList();
      int a = sd[0]; int b = sd[1];
      List<int> sd1 = Console.ReadLine().Split().Select(int.Parse).ToList();
      int c = sd1[0]; int d = sd1[1];
      List<int> aa = new List<int>();
      List<int> bb = new List<int>();

      int br = 0;
      for (int i = 0; i < 100; i++)
      {
        aa.Add(b + i * a);
        bb.Add(d + i * c);
      }

      for (int i = 0; i < 100; i++)
      {
        for (int j = 0; j < 100; j++)
        {
          if (aa[i] == bb[j]) {
            br++; Console.WriteLine(aa[i]);
            return;
          }
        }
      }

      if (br == 0) Console.WriteLine("-1");
    }
  }
}

using System;

namespace CodeForce
{
    class Program
    {
        static void Main()
        {
            var inputRick = Console.ReadLine();
            var inputMorti = Console.ReadLine();
            var varsRick = inputRick.Split(' ');
            var varsMorti = inputMorti.Split(' ');
            int a = int.Parse(varsRick[0]),
                b = int.Parse(varsRick[1]),
                c = int.Parse(varsMorti[0]),
                d = int.Parse(varsMorti[1]),
                result = 0;
            int i = 0, j = 0;

            while (true) {

                var timeRick = b + i * a;
                var timeMorti = d + j * c;

                while (timeRick < timeMorti) {
                    i++;
                    timeRick = b + i * a;
                }

                while (timeMorti < timeRick) {
                    j++;
                    timeMorti = d + j * c;
                }
                if (timeRick == timeMorti) {
                    result = b + i * a;
                    break;
                }

                if (timeRick >= 100000000 || timeMorti >= 100000000) {
                    result = -1;
                    break;
                }
            }
            Console.WriteLine(result);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace TaskA
{
    class Program
    {
        static void Main(string[] args)
        {
            new Solver().Solve().OutputResult();
        }

        private class ExtendedReader : StreamReader
        {
            private static readonly char Separator = ' ';

            public ExtendedReader(Stream stream) : base(stream) { }
            public ExtendedReader(Stream stream, bool detectEncodingFromByteOrderMarks) : base(stream, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(Stream stream, Encoding encoding) : base(stream, encoding) { }
            public ExtendedReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) : base(stream, encoding, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) : base(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize) { }
            public ExtendedReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) : base(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen) { }
            public ExtendedReader(string path) : base(path) { }
            public ExtendedReader(string path, bool detectEncodingFromByteOrderMarks) : base(path, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(string path, Encoding encoding) : base(path, encoding) { }
            public ExtendedReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) : base(path, encoding, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) : base(path, encoding, detectEncodingFromByteOrderMarks, bufferSize) { }

            public char ReadChar()
            {
                return (char)this.Read();
            }

            public double ReadDoubleFromArray()
            {
                StringBuilder sb = new StringBuilder();
                char ch = this.ReadChar();
                while (ch != Separator && ch != '\n')
                {
                    sb.Append(ch);
                    ch = this.ReadChar();
                }
                return Convert.ToDouble(sb.ToString());
            }

            public int ReadInt()
            {
                return int.Parse(this.ReadLine());
            }

            public Int64 ReadInt64()
            {
                return Int64.Parse(this.ReadLine());
            }

            public int[] ReadIntArray()
            {
                return this.ReadLine().Split(' ').Select(int.Parse).ToArray();
            }

            public char[] ReadCharArray()
            {
                return this.ReadLine().ToCharArray();
            }

            public string ReadString()
            {
                return this.ReadLine();
            }

            public Int64[] ReadInt64Array()
            {
                return this.ReadLine().Split(Separator).Select(Int64.Parse).ToArray();
            }

            public Double[] ReadDoubleArray()
            {
                return this.ReadLine().Split(Separator).Select(Double.Parse).ToArray();
            }
        }

        private abstract class SolverBase
        {
            protected readonly ExtendedReader _reader;
            protected readonly TextWriter _writer;

            protected SolverBase()
            {
#if DEBUG
                _reader = new ExtendedReader("input.txt");
                //_writer = new StreamWriter("output.txt");
                _writer = new StreamWriter(Console.OpenStandardOutput());
#else
                _reader = new ExtendedReader(Console.OpenStandardInput());
                _writer = new StreamWriter(Console.OpenStandardOutput());
#endif
            }

            public abstract Solver Solve();

            public abstract void OutputResult();
        }

        private class Solver : SolverBase
        {
            private int result = -1;

            public override Solver Solve()
            {
                // link to task: http://codeforces.com/contest/787/problem/0

                var input = _reader.ReadIntArray();
                var a = input[0];
                var b = input[1];
                input = _reader.ReadIntArray();
                var c = input[0];
                var d = input[1];

                var first = new HashSet<int>();
                for (int i = 0; i <= 10000; i++)
                {
                    first.Add(b + i * a);
                }

                int j = 0;
                for (int i = 0; i < 10000; i++)
                {
                    var number = d + i * c;
                    if (first.Contains(number))
                    {
                        result = number;
                        break;
                    }
                }

                return this;
            }

            public override void OutputResult()
            {
                string answer = result.ToString(CultureInfo.InvariantCulture);

                _writer.WriteLine(answer);
                _writer.Dispose();
            }
        }
    }
}

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Codeforces
{
	internal class Template
	{
		private void Solve()
		{
			var a = cin.NextLong();
			var b = cin.NextLong();
			var c = cin.NextLong();
			var d = cin.NextLong();
			var bb = b;
			var dd = d;
			var counter = (int) 10e7;
			while (bb != dd)
			{
				if (bb < dd)
				{
					bb += a;
				}
				else
				{
					dd += c;
				}
				counter--;
				if (counter == 0)
				{
					Console.WriteLine(-1);
					return;
				}
			}
			Console.WriteLine(bb);
		}

		private static readonly Scanner cin = new Scanner();

		private static void Main()
		{
#if DEBUG
			var inputText = File.ReadAllText(@"..\..\input.txt");
			var testCases = inputText.Split(new[] { "input" }, StringSplitOptions.RemoveEmptyEntries);
			var consoleOut = Console.Out;
			for (var i = 0; i < testCases.Length; i++)
			{
				var parts = testCases[i].Split(new[] { "output" }, StringSplitOptions.RemoveEmptyEntries);
				Console.SetIn(new StringReader(parts[0].Trim()));
				var stringWriter = new StringWriter();
				Console.SetOut(stringWriter);
				var sw = Stopwatch.StartNew();
				new Template().Solve();
				sw.Stop();
				var output = stringWriter.ToString();

				Console.SetOut(consoleOut);
				var color = ConsoleColor.Green;
				var status = "Passed";
				if (parts[1].Trim() != output.Trim())
				{
					color = ConsoleColor.Red;
					status = "Failed";
				}
				Console.ForegroundColor = color;
				Console.WriteLine("Test {0} {1} in {2}ms", i + 1, status, sw.ElapsedMilliseconds);
			}
			Console.ReadLine();
			Console.ReadKey();
#else
			new Template().Solve();
			Console.ReadLine();
#endif
		}
	}

	internal class Scanner
	{
		private string[] s = new string[0];
		private int i;
		private readonly char[] cs = { ' ' };

		public string NextString()
		{
			if (i < s.Length) return s[i++];
			var line = Console.ReadLine() ?? string.Empty;
			s = line.Split(cs, StringSplitOptions.RemoveEmptyEntries);
			i = 1;
			return s.First();
		}

		public double NextDouble()
		{
			return double.Parse(NextString());
		}

		public int NextInt()
		{
			return int.Parse(NextString());
		}

		public long NextLong()
		{
			return long.Parse(NextString());
		}
	}
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

class Solution
{

    static void Main(String[] args)
    {
        var l = Console.ReadLine().Split();
        int a = int.Parse(l[0]);
        int b = int.Parse(l[1]);
        l = Console.ReadLine().Split();
        int c = int.Parse(l[0]);
        int d = int.Parse(l[1]);
        for (int i = 0; i < 100; i++)
        {
            for (int j = 0; j < 100; j++)
            {
                if (b + a * i == d+ c * j)
                {
                    Console.WriteLine(b + a * i);
                    Console.Read();
                    return;
                }
            }
        }
        Console.WriteLine(-1);
        Console.Read();
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testik
{
    class Program
    {

        static void Main(string[] args)
        {
            int[] ar = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int a = ar[0];
            int b = ar[1];
            ar = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int c = ar[0];
            int d = ar[1];
            int i = 10000;

            while (i > 0)
            {
                if (b < d)
                {
                    b += a;
                }
                else
                {
                    if (b > d)
                    {
                        d += c;
                    }
                    else
                    {
                        Console.WriteLine(d);
                        return;
                    }
                }
                i--;
            }
            Console.WriteLine(-1);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace index
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Ric = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int[] Martin = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int sumRic = Ric[0] + Ric[1];
            int sumMartin = Martin[0] + Martin[1];

            int res = 0;

            if((sumMartin % 2 == 0 && Martin[1] % 2 == 0 && sumRic % 2 != 0 && Ric[1] % 2 != 0) || (sumMartin % 2 != 0 && Martin[1] % 2 != 0 && sumRic % 2 == 0 && Ric[1] % 2 == 0))
            {
                res = -1;
            }
            else
            {
                int M = Martin[1];
                int R = Ric[1];
                int i = 1;
                int j = 1;

                if (M > R)
                {
                    while (R != M)
                    {
                        while (R < M)
                        {
                            R = Ric[1] + Ric[0] * i;
                            i++;
                        }
                        if (R != M)
                        {
                            M = Martin[1] + Martin[0] * j;
                            j++;
                        }
                        if(M > 20000)
                        {
                            res = -1;
                            break;
                        }
                    }
                    if (res != -1)
                    {
                        res = M;
                    }
                }
                else if (R > M)
                {
                    while (R != M)
                    {
                        while (R > M)
                        {
                            M = Martin[1] + Martin[0] * i;
                            i++;
                        }
                        if (R != M)
                        {
                            R = Ric[1] + Ric[0] * j;
                            j++;
                        }
                        if(R > 20000)
                        {
                            res = -1;
                            break;
                        }
                    }
                    if (res != -1)
                    {
                        res = M;
                    }
                }
                else
                {
                    res = M;
                }
            }

            Console.WriteLine(res);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nastya
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] data1 = (Console.ReadLine()).Split(' ');
            string[] data2 = (Console.ReadLine()).Split(' ');

            int a = int.Parse(data1[0]);
            int b = int.Parse(data1[1]);

            int c = int.Parse(data2[0]);
            int d = int.Parse(data2[1]);

            Console.WriteLine(result(a, b, c, d));

        }

        static int result(int a, int b, int c, int d)
        {
            for (int i = 0; i <=100; i++)
            {
                int RickTime = (b + i * a);

                for (int j = 0; j < 100; j++)
                {
                    int MotriTime = (d + j * c);

                    if (RickTime == MotriTime)
                    {
                        return MotriTime;
                    }
                }
            }

            return -1;
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {

        static void Main(string[] args)
        {
            var s = Console.ReadLine().Split();

            int a = int.Parse(s[0]), b = int.Parse(s[1]);
            s = Console.ReadLine().Split();
            int c = int.Parse(s[0]), d = int.Parse(s[1]);
            int i = 10000000;

            while (i > 0)
            {
                if (b < d)
                {
                    b += a;
                }
                else
                    if (b > d)
                    {
                        d += c;
                    }
                    else
                    {
                        Console.WriteLine(b);
                        return;
                    }
                i--;
            }
            Console.WriteLine(-1);

        }

    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace The_Monster
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            int a = Next();
            int b = Next();
            int c = Next();
            int d = Next();

            var nn = new List<int>();
            for (; b < 100000;)
            {
                nn.Add(b);
                b += a;
            }
            for (; d < 100000;)
            {
                if (nn.BinarySearch(d) >= 0)
                {
                    writer.WriteLine(d);
                    writer.Flush();
                    return;
                }
                d += c;
            }

            writer.WriteLine("-1");
            writer.Flush();
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
    }
}

using System;

namespace _787A
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input1 = Console.ReadLine().Split(' '), input2 = Console.ReadLine().Split(' ');
            decimal a = decimal.Parse(input1[0]), b = decimal.Parse(input1[1]);
            decimal c = decimal.Parse(input2[0]), d = decimal.Parse(input2[1]);
            bool result = false;
            for (decimal y = 0; y <= 100000; y++)
            {
                decimal x = (d + y * c - b) / a;
                if (x >= 0 && x == Math.Floor(x))
                {
                    Console.WriteLine((b + x * a).ToString());
                    result = true;
                    break;
                }
            }
            if (!result) Console.WriteLine("-1");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace CF317
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var sr = new InputReader(Console.In);
            //var sr = new InputReader(new StreamReader("input.txt"));
            var task = new Task();
            using (var sw = Console.Out)
            {
                //using (var sw = new StreamWriter("output.txt")) {
                task.Solve(sr, sw);
                //Console.ReadKey();
            }
        }
    }

    internal class Task
    {
        public void Solve(InputReader sr, TextWriter sw)
        {
            var input = sr.ReadArray(Int32.Parse);
            var a = input[0];
            var b = input[1];
            input = sr.ReadArray(Int32.Parse);
            var c = input[0];
            var d = input[1];
            for (var i = 0; i < 1000; i++) {
                var t1 = b + a * i;
                for (var j = 0; j < 1000; j++) {
                    var t2 = d + c * j;
                    if (t1 == t2) {
                        sw.WriteLine(t1);
                        return;
                    }
                }
            }

            sw.WriteLine(-1);
        }
    }
}

internal class InputReader : IDisposable
{
    private bool isDispose;
    private readonly TextReader sr;

    public InputReader(TextReader stream)
    {
        sr = stream;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public string NextString()
    {
        var result = sr.ReadLine();
        return result;
    }

    public int NextInt32()
    {
        return Int32.Parse(NextString());
    }

    public long NextInt64()
    {
        return Int64.Parse(NextString());
    }

    public string[] NextSplitStrings()
    {
        return NextString()
                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    }

    public T[] ReadArray<T>(Func<string, CultureInfo, T> func)
    {
        return NextSplitStrings()
                .Select(s => func(s, CultureInfo.InvariantCulture))
                .ToArray();
    }

    public T[] ReadArrayFromString<T>(Func<string, CultureInfo, T> func, string str)
    {
        return
                str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => func(s, CultureInfo.InvariantCulture))
                        .ToArray();
    }

    protected void Dispose(bool dispose)
    {
        if (!isDispose)
        {
            if (dispose)
                sr.Close();
            isDispose = true;
        }
    }

    ~InputReader()
    {
        Dispose(false);
    }
}

using System;
using System.Linq;

namespace _100853_Codeforce
{

    class Program
    {

        static void Main(string[] args)
        {
            int[] array = Console.ReadLine().Split(' ')
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Select(int.Parse).ToArray();
            int a = array[0];
            int b = array[1];
            array = Console.ReadLine().Split(' ')
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Select(int.Parse).ToArray();
            int c = array[0];
            int d = array[1];

            for(int i = 10000; i > 0; i--)
            {
                if (b < d)
                {
                    b += a;
                }
                else
                {
                    if (b > d)
                    {
                        d += c;
                    }
                    else
                    {
                        Console.WriteLine(d);
                        return;
                    }
                }
            }

            Console.WriteLine(-1);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Point : IComparable<Point>
    {
        public int Index { get; set; }
        public decimal Andle { get; set; }
        public Point(decimal angle, int index)
        {
            Index = index;
            Andle = angle;
        }
        public int CompareTo(Point other)
        {
            return this.Andle.CompareTo(other.Andle);
        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split();
            long a = long.Parse(s[0]);
            long b = long.Parse(s[1]);
            s = Console.ReadLine().Split();
            long c = long.Parse(s[0]);
            long d = long.Parse(s[1]);
            int[] mas = new int[10000001];
            mas[b] = 1;
            while (b < mas.Length)
            {
                mas[b] = 1;
                b += a;
            }
            if (mas[d] == 1)
            {
                Console.WriteLine(d);
                return;
            }

            while (d < mas.Length)
            {
                if (mas[d] == 1)
                {
                    Console.WriteLine(d);
                    return;
                }
                d += c;

            }
            Console.WriteLine(-1);
        }
    }
}
/*7 3 0 0
1 2 2 3 4 5 6
2 2 3*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Monsters
{
    static void Main()
    {
        List<int> pesho = Console.ReadLine().Split().Select(int.Parse).ToList();
        List<int> gosho = Console.ReadLine().Split().Select(int.Parse).ToList();

        int a = pesho[0];
        int b = pesho[1];
        int c = gosho[0];
        int d = gosho[1];

        int peshoC;
        int goshoC;

        Dictionary<int, int> screamers = new Dictionary<int, int>();

        int MaxTime = (int)Math.Pow(100,2)+1;
        int Result = -1;

        for (int i = 0; i < MaxTime; i++)
        {
            peshoC = b + a * i;
            goshoC = d + c * i;
            if (!screamers.ContainsKey(peshoC))
            {
                screamers.Add(peshoC, 1);
            }
            else
            {
                Result = peshoC;
                break;
            }
            if (!screamers.ContainsKey(goshoC))
            {
                screamers.Add(goshoC, 1);
            }
            else
            {
                Result = goshoC;
                break;
            }
        }
        Console.WriteLine(Result);
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Monsters
{
    static void Main()
    {
        List<int> pesho = Console.ReadLine().Split().Select(int.Parse).ToList();
        List<int> gosho = Console.ReadLine().Split().Select(int.Parse).ToList();

        int a = pesho[0];
        int b = pesho[1];
        int c = gosho[0];
        int d = gosho[1];
        Dictionary<int, int> screamers = new Dictionary<int, int>();
        int MaxTime = 100 ^ 2+1;
        int Result = -1;

        for (int i = 0; i < MaxTime; i++)
        {
            if (!screamers.ContainsKey(b + a * i))
            {
                screamers.Add(b + a * i, 1);
            }
            else
            {
                Result = b + a * i;
                break;
            }
            if (!screamers.ContainsKey(d + c * i))
            {
                screamers.Add(d+ c * i, 1);
            }
            else
            {
                Result = d + c * i;
                break;
            }
        }
        Console.WriteLine(Result);
    }
}

using System;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            //Dados
            string txt = Console.ReadLine();
            int a = int.Parse(txt.Split()[0]), b = int.Parse(txt.Split()[1]);
            txt = Console.ReadLine();
            int c = int.Parse(txt.Split()[0]), d = int.Parse(txt.Split()[1]);
            bool achou = false;
            int resultado = 0;

            //O conjunto que pode abranger o resultado é incalculavel
            for(int i = 0; i < 1000 ; i++)
            {
                for(int j = 0; j < 1000; j++)
                {
                    if(b + a * i == d + c * j)
                    {
                        resultado = b + a * i;
                        achou = true;
                        break;
                    }
                }
                if (achou)
                    break;
            }

            if (achou)
                Console.Write(resultado);
            else
                Console.Write(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Deneme
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int[] ab = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                int[] cd = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                int rtime = ab[1];
                int mtime = cd[1];
                while (rtime != mtime && rtime < 100000)
                {
                    while (rtime < mtime)
                        rtime += ab[0];
                    while (mtime < rtime)
                        mtime += cd[0];
                }
                if (rtime >= 100000)
                    Console.WriteLine("-1");
                else
                    Console.WriteLine(rtime);
                Console.ReadKey();
            }
            catch { }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading;
using System.Collections;
using System.Linq;
using System.Text;

#pragma warning disable

class Segtree<T>
{
    int n;
    T[] tree;
    Func<T, T, T> f;
    T exnum;
    public Segtree(int m, Func<T, T, T> f, T ex)
    {
        this.f = f;
        this.exnum = ex;
        n = 1;
        while (n < m) n <<= 1;

        tree = new T[(n << 1) - 1];
        for (int i = 0; i < tree.Length; i++) tree[i] = ex;
    }
    public Segtree(int m, T ini, Func<T, T, T> f, T ex)
    {
        this.f = f;
        this.exnum = ex;
        n = 1;
        while (n < m) n <<= 1;

        tree = new T[(n << 1) - 1];
        for (int i = 0; i < tree.Length; i++) tree[i] = ini;
        for (int i = 0; i < m; ++i) update(i, ini);
    }
    public void update(int j, T x)
    {
        int i = j + n - 1;
        tree[i] = x;
        while (i > 0)
        {
            i = (i - 1) >> 1;
            tree[i] = f(tree[(i << 1) + 1], tree[(i << 1) + 2]);
        }
    }
    public T look(int i) { return tree[i + n - 1]; }

    // [s, t]
    public T run(int s, int t) { return query(s, t + 1, 0, 0, n); }
    T query(int s, int t, int k, int l, int r)
    {
        if (r <= s || t <= l) return exnum;
        if (s <= l && r <= t) return tree[k];

        return f(query(s, t, (k << 1) + 1, l, (l + r) >> 1), query(s, t, (k + 1) << 1, (l + r) >> 1, r));
    }
}

class PriorityQueue<T>
{
    private Comparison<T> comp;
    private List<T> list;
    private int count;
    public PriorityQueue() : this((x, y) => ((IComparable<T>)x).CompareTo(y)) { }
    public PriorityQueue(Comparison<T> comparison)
    {
        comp = comparison;
        list = new List<T>();
        count = 0;
    }
    public void Enqueue(T x)
    {
        var pos = count++;
        list.Add(x);
        while (pos > 0)
        {
            var p = (pos - 1) / 2;
            if (comp(list[p], x) <= 0) break;
            list[pos] = list[p];
            pos = p;
        }
        list[pos] = x;
    }
    public T Dequeue()
    {
        var value = list[0];
        var x = list[--count];
        list.RemoveAt(count);
        if (count == 0) return value;
        var pos = 0;
        while (pos * 2 + 1 < count)
        {
            var a = 2 * pos + 1;
            var b = 2 * pos + 2;
            if (b < count && comp(list[b], list[a]) < 0) a = b;
            if (comp(list[a], x) >= 0) break;
            list[pos] = list[a];
            pos = a;
        }
        list[pos] = x;
        return value;
    }
    public T Peek() { return list[0]; }
    public bool Any() { return count > 0; }
    public int Count() { return count; }
}

namespace Codeforces
{
    class Program
    {
        class mymath
        {
            static int Mod = 1000000007;
            public void setMod(int m) { Mod = m; }
            public bool isprime(long a)
            {
                if (a < 2) return false;
                for (long i = 2; i * i <= a; i++) if (a % i == 0) return false;
                return true;
            }
            public bool[] sieve(int n)
            {
                var isp = new bool[n + 1];
                for (int i = 2; i <= n; i++) isp[i] = true;
                for (int i = 2; i * i <= n; i++) if (isp[i]) for (int j = i * i; j <= n; j += i) isp[j] = false;
                return isp;
            }
            public List<int> getprimes(int n)
            {
                var prs = new List<int>();
                var isp = sieve(n);
                for (int i = 2; i <= n; i++) if (isp[i]) prs.Add(i);
                return prs;
            }
            public long[][] E(int n)
            {
                var ret = new long[n][];
                for (int i = 0; i < n; i++)
                {
                    ret[i] = new long[n];
                    ret[i][i] = 1;
                }
                return ret;
            }
            public long[][] powmat(long[][] A, long n)
            {
                if (n == 0) return E(A.Length);
                var t = powmat(A, n / 2);
                if ((n & 1) == 0) return mulmat(t, t);
                return mulmat(mulmat(t, t), A);
            }
            public long[] mulmat(long[][] A, long[] x)
            {
                int n = A.Length, m = x.Length;
                var ans = new long[n];
                for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ans[i] = (ans[i] + x[j] * A[i][j]) % Mod;
                return ans;
            }
            public long[][] mulmat(long[][] A, long[][] B)
            {
                int n = A.Length, m = B[0].Length, l = B.Length;
                var ans = new long[n][];
                for (int i = 0; i < n; i++)
                {
                    ans[i] = new long[m];
                    for (int j = 0; j < m; j++) for (int k = 0; k < l; k++) ans[i][j] = (ans[i][j] + A[i][k] * B[k][j]) % Mod;
                }
                return ans;
            }
            public long[] addmat(long[] x, long[] y)
            {
                int n = x.Length;
                var ans = new long[n];
                for (int i = 0; i < n; i++) ans[i] = (x[i] + y[i]) % Mod;
                return ans;
            }
            public long[][] addmat(long[][] A, long[][] B)
            {
                int n = A.Length, m = A[0].Length;
                var ans = new long[n][];
                for (int i = 0; i < n; i++) ans[i] = addmat(A[i], B[i]);
                return ans;
            }
            public long powmod(long a, long b)
            {
                if (a >= Mod) return powmod(a % Mod, b);
                if (a == 0) return 0;
                if (b == 0) return 1;
                var t = powmod(a, b / 2);
                if ((b & 1) == 0) return t * t % Mod;
                return t * t % Mod * a % Mod;
            }
            public long inv(long a) { return powmod(a, Mod - 2); }
            public long gcd(long a, long b)
            {
                while (b > 0) { var t = a % b; a = b; b = t; }
                return a;
            }
            public long lcm(long a, long b) { return a * (b / gcd(a, b)); }
            public long Comb(int n, int r)
            {
                if (n < 0 || r < 0 || r > n) return 0;
                if (n - r < r) r = n - r;
                if (r == 0) return 1;
                if (r == 1) return n;
                var numerator = new int[r];
                var denominator = new int[r];
                for (int k = 0; k < r; k++)
                {
                    numerator[k] = n - r + k + 1;
                    denominator[k] = k + 1;
                }
                for (int p = 2; p <= r; p++)
                {
                    int pivot = denominator[p - 1];
                    if (pivot > 1)
                    {
                        int offset = (n - r) % p;
                        for (int k = p - 1; k < r; k += p)
                        {
                            numerator[k - offset] /= pivot;
                            denominator[k] /= pivot;
                        }
                    }
                }
                long result = 1;
                for (int k = 0; k < r; k++) if (numerator[k] > 1) result = result * numerator[k] % Mod;
                return result;
            }
        }

        const long InfL = 4011686018427387913L;
        static char[] sep = new char[] { ' ', '/' };

        //static int[] dx = { -1, 0, 1, -1, 1, -1, 0, -1 };
        //static int[] dy = { 1, 1, 1, 0, 0, -1, -1, -1 };

        static int[] dx = { -1, 0, 0, 1 };
        static int[] dy = { 0, 1, -1, 0 };

        /// <summary>
        /// basic dfs function
        /// </summary>
        ///
        /* public class List_of_List<T> : List<List<T>> { }
        static int result = 0;

        static List<bool> visited = new List<bool>();
        static List_of_List<int> adj = new List_of_List<int>();
        static Stack<string> route = new Stack<string>();

        static void dfs(int here)
        {
            if (here == n * m - 1)
            {
                result++;
                return;
            }
            visited[here] = true;

            for(int i = 0; i<adj[here].Count; i++)
            {
                int there = adj[here][i];
                if (!visited[there])
                    dfs(there);
                visited[there] = false;
            }
        }

        static void dfsAll()
        {
            for(int i = 0; i<adj.Count; i++)
            {
                dfs(i);
            }
        }

        /* static int getInt => int.Parse(Console.ReadLine());
        static int[] getIntArr => Console.ReadLine().Trim().Split(sep).Select(a => int.Parse(a)).ToArray();
        static List<int> getIntList => Console.ReadLine().Trim().Split(sep).Select(a => int.Parse(a)).ToList<int>();
        static string getString => Console.ReadLine().Trim();
        static string[] getStrArr => Console.ReadLine().Trim().Split(sep);
        static List<string> getStrList => Console.ReadLine().Trim().Split(sep).ToList<string>();
        */
        static int m;
        static int n;
        static int[] input = new int[100001];

        [Flags]
        enum days
        {
            Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64
        }

        delegate void calcDelegate(int x, int y);

        static void Add(int x, int y) { Console.WriteLine( x + y); }
        static void Sub(int x, int y) { Console.WriteLine( x - y); }
        static void Mult(int x, int y) { Console.WriteLine( x * y); }
        static void Div(int x, int y) { Console.WriteLine( x / y); }

        public class List_of_List<T> : List<List<T>> { }
        static List<int> distance = new List<int>();
        static List<int> parent = new List<int>();
        static List_of_List<int> adj = new List_of_List<int>();

        static void bfs(int start, List<int> distance)
        {
            Queue<int> q = new Queue<int>();
            List<int> order = new List<int>();
            distance[start] = 0;
            parent[start] = start;
            q.Enqueue(start);
            while(q.Count != 0)
            {
                int here = q.Dequeue();
                order.Add(here);
                for(int i = 0; i<adj[here].Count; i++)
                {
                    int there = adj[here][i];
                    if (distance[there] == -1)
                    {
                        q.Enqueue(there);
                        distance[there] = distance[here] + 1;
                        parent[there] = here;
                    }
                }
            }
        }

        static List<int> shortestPath(int v, List<int> parent)
        {
            List<int> path = new List<int>();
            path.Add(v);

            while(parent[v] != v)
            {
                v = parent[v];
                path.Add(v);
            }
            path.Reverse();
            return path;
        }

        static void Main(string[] args)
        {
            int[] rick = Console.ReadLine().Trim().Split(sep).Select(a => int.Parse(a)).ToArray();
            int[] morty = Console.ReadLine().Trim().Split(sep).Select(a => int.Parse(a)).ToArray();

            List<int> rick_list = new List<int>();
            List<int> morty_list = new List<int>();

            int rick_pos = rick[1];
            int morty_pos = morty[1];

            while(rick_pos <= 10000)
            {
                rick_list.Add(rick_pos);
                rick_pos += rick[0];
            }
            while (morty_pos <= 10000)
            {
                morty_list.Add(morty_pos);
                morty_pos += morty[0];
            }

            foreach(int i in rick_list)
            {
                if (morty_list.Contains(i))
                {
                    Console.WriteLine(i);
                    return;
                }
            }
            Console.WriteLine(-1);

        }

        static void CountPrimeNumbers(object initialValue)
        {
            string value = (string)initialValue;

            int primeCandidate = int.Parse(value);

            int totalPrimes = 0;

            for(int i = 2; i<primeCandidate; i++)
            {
                if(IsPrime(i) == true)
                {
                    totalPrimes++;
                }
            }

            Console.WriteLine("숫자 {0}까지의 소수 개수? {1}", value, totalPrimes);
        }

        static bool IsPrime(int candidate)
        {
            if ((candidate & 1 ) == 0) return candidate == 2;
            for(int i = 3; (i*i) <= candidate; i += 2)
            {
                if (candidate % i == 0) return false;
            }
            return candidate != 1;
        }
        /*
        /// <summary>
        /// 이분 매칭 알고리즘
        /// </summary>

        static bool[,] adj; // 연결 리스트. 이분 매칭이기 때문에 bool 형식이다. 혹-시라도 타임아웃이 뜬다면 인접리스트로 바꿔볼 것. 조금 빨라진다.
        static List<bool> visited; // 왼쪽의 한 정점에서 오른쪽의 모든 정점으로 방문 기록을 정리하는 리스트
        static List<int> m_match; // 왼쪽에 있는 정점들의 집합
        static List<int> n_match; // 오른쪽에 있는 정점들의 집합

        static bool dfs(int a) // 왼쪽 정점 a 에서 오른쪽 정점으로 가는 경로를 찾는다
        {
            if (visited[a]) return false;
            visited[a] = true;
            for (int b = 0; b < n; b++)
            {
                if (adj[a, b]) // 왼쪽 정점 a 에서 오른쪽 정점중 b에 연결할 수 있는 경우
                {
                    if (n_match[b] == -1 || dfs(n_match[b])) // b가 이미 매칭되어 있다면 n_match[b]에서 시작되는 증가경로를 찾는다
                    {
                        // 증가 경로를 발견한 경우 a와 b를 매치시키고 true를 반환한다
                        m_match[a] = b;
                        n_match[b] = a;
                        return true;
                    }
                }
            }
            return false;
        }

        static int bipartite_match()
        {
            m_match = Enumerable.Repeat(-1, m).ToList(); // 왼쪽에 있는 정점들의 각 원소가 오른쪽에 있는 어떤 정점과 대응되는지 기록하는 리스트
            n_match = Enumerable.Repeat(-1, n).ToList(); // 오른쪽에 있는 정점들의 각 원소가 왼쪽에 있는 어떤 정점과 대응되는지 기록하는 리스트

            int size = 0; // 몇 쌍이 대응되는지 기록하는 변수
            for (int start = 0; start < m; start++) // m_match (왼쪽에 있는 정점들 집합) 의 모든 원소에 대해 dfs 실시
            {
                visited = Enumerable.Repeat(false, m).ToList(); // 모든 점에 대해 초기화 (방문하지 않음으로 표시)

                if (dfs(start)) size++; // 각 왼쪽 정점에서 dfs를 실시해서 갈 수 있는 경로가 있다면 경로의 개수를 1 늘린다
            }
            return size;
        }
        */

        /*
        /// <summary>
        /// 네트워크 유량 문제용 포드-풀커슨 알고리즘
        /// </summary>

        const int INF = 987654321;
        static int v; // 정점의 수. source와 sink가 있으므로 감안해서 계산
        static int max_v;
        static int[,] capacity, flow;
        // capacity[u,v] = u에서 v로 보낼 수 있는 용량, flow[u,v] = u에서 v로 흘러가는 유량 (반대방향인 경우 음수)

        // flow[,] 를 계산하고 총 유량을 반환하는 함수
        static int networkFlow(int source, int sink)
        {
            flow = new int[max_v, max_v]; // flow 배열의 초기화
            int totalFlow = 0;
            while (true)
            {
                List<int> parent = Enumerable.Repeat(-1, max_v).ToList();
                Queue<int> q = new Queue<int>();
                parent[source] = source;
                q.Enqueue(source);
                while (q.Count != 0 && parent[sink] == -1)
                {
                    int here = q.Dequeue();
                    for (int there = 0; there < v; there++)
                    {
                        if (capacity[here, there] - flow[here, there] > 0 && parent[there] == -1)
                        {
                            q.Enqueue(there);
                            parent[there] = here;
                        }
                    }
                }

                if (parent[sink] == -1) break;

                int amount = INF;
                for(int p = sink; p != source; p = parent[p])
                {
                    amount = Math.Min(capacity[parent[p], p] - flow[parent[p], p], amount);
                }
                for(int p = sink; p != source; p = parent[p])
                {
                    flow[parent[p], p] += amount;
                    flow[p, parent[p]] -= amount;
                }

                totalFlow += amount;
            }
            return totalFlow;
        }
        */
    }
}

using System;
using System.Collections.Generic;
//using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

//using System.Threading;

namespace ReadWriteTemplate
{
    public static class Solver
    {
        public static void Solve()
        {
            int a = ReadInt();
            int b = ReadInt();
            int c = ReadInt();
            int d = ReadInt();

            int N = 1000000;
            bool[] u = new bool[N];
            for (int i = b; i < N; i += a)
            {
                u[i] = true;
            }
            for (int i = d; i < N; i += c)
            {
                if (u[i])
                {
                    Writer.WriteLine(i);
                    return;
                }
            }
            Writer.WriteLine(-1);
        }

        public static void Main()
        {
            //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

#if DEBUG
            Reader = File.OpenText("input.txt"); Writer = File.CreateText("output.txt");
#else
            Reader = Console.In; Writer = Console.Out;
#endif
            //Reader = File.OpenText("concatenation.in"); Writer = File.CreateText("concatenation.out");

            Solve();

            Reader.Close();
            Writer.Close();
        }

        public static IOrderedEnumerable<TSource> OrderByWithShuffle<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            return source.Shuffle().OrderBy(keySelector);
        }

        public static T[] Shuffle<T>(this IEnumerable<T> source)
        {
            T[] result = source.ToArray();
            Random rnd = new Random();
            for (int i = result.Length - 1; i >= 1; i--)
            {
                int k = rnd.Next(i + 1);
                T tmp = result[k];
                result[k] = result[i];
                result[i] = tmp;
            }
            return result;
        }

#region Read/Write

        private static TextReader Reader;

        private static TextWriter Writer;

        private static Queue<string> CurrentLineTokens = new Queue<string>();

        private static string[] ReadAndSplitLine()
        {
            return Reader.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        }

        public static string ReadToken()
        {
            while (CurrentLineTokens.Count == 0)
                CurrentLineTokens = new Queue<string>(ReadAndSplitLine());
            return CurrentLineTokens.Dequeue();
        }

        public static string ReadLine()
        {
            return Reader.ReadLine();
        }

        public static int ReadInt()
        {
            return int.Parse(ReadToken());
        }

        public static long ReadLong()
        {
            return long.Parse(ReadToken());
        }

        public static double ReadDouble()
        {
            return double.Parse(ReadToken(), CultureInfo.InvariantCulture);
        }

        public static int[] ReadIntArray()
        {
            return ReadAndSplitLine().Select(int.Parse).ToArray();
        }

        public static long[] ReadLongArray()
        {
            return ReadAndSplitLine().Select(long.Parse).ToArray();
        }

        public static double[] ReadDoubleArray()
        {
            return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
        }

        public static int[][] ReadIntMatrix(int numberOfRows)
        {
            int[][] matrix = new int[numberOfRows][];
            for (int i = 0; i < numberOfRows; i++)
                matrix[i] = ReadIntArray();
            return matrix;
        }

        public static string[] ReadLines(int quantity)
        {
            string[] lines = new string[quantity];
            for (int i = 0; i < quantity; i++)
                lines[i] = Reader.ReadLine().Trim();
            return lines;
        }

        public static void WriteArray<T>(IEnumerable<T> array)
        {
            Writer.WriteLine(string.Join(" ", array));
        }

#endregion
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication22
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] reader = Console.ReadLine().Split(' ');
            int a = int.Parse(reader[0]), b = int.Parse(reader[1]);

            reader = Console.ReadLine().Split(' ');
            int c = int.Parse(reader[0]), d = int.Parse(reader[1]);

            int output = -1;

            var X1 = Enumerable.Range(0, 101).Select(x => b + (x * a)).ToList();
            var X2 = Enumerable.Range(0, 101).Select(x => d + (x * c)).ToList();
            var mp = new List<int>();

            if (a > c)
            {
                mp = X1.Intersect(X2).ToList();
            }
            else
            {
                mp = X2.Intersect(X1).ToList();
            }
            output = mp.Count > 0 ? mp.First() : -1;
            Console.WriteLine(output);
        }
    }
}

using System;

namespace CSharp
{
    public class _787A
    {
        public static void Main()
        {
            string[] tokens = Console.ReadLine().Split();

            int a = int.Parse(tokens[0]);
            int b = int.Parse(tokens[1]);

            tokens = Console.ReadLine().Split();

            int c = int.Parse(tokens[0]);
            int d = int.Parse(tokens[1]);

            while (b < 10000 && d < 10000 && b != d)
            {
                if (b < d)
                {
                    b += a;
                }
                else
                {
                    d += c;
                }
            }

            Console.WriteLine(b == d ? b : -1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class examples
    {
        static void Main(string[] args)
        {
            int f, g;
            string[] rick = Console.ReadLine().Split();
            string[] morty = Console.ReadLine().Split();
            for (int i = 0; i < 1000; i++)
            {
                f = int.Parse(rick[1]) + i * int.Parse(rick[0]);
                for (int j = 0; j < 1000; j++)
                {
                    g = int.Parse(morty[1]) + j * int.Parse(morty[0]);
                    if (g == f)
                    {
                        Console.Write(f);
                        goto A;
                    }
                }
            }

            Console.Write(-1);
        A:;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class examples
    {
        static void Main(string[] args)
        {
            int r, m, a, b, f, g;
            string[] rick = Console.ReadLine().Split();
            string[] morty = Console.ReadLine().Split();
            r = int.Parse(rick[0]);
            a = int.Parse(rick[1]);
            m = int.Parse(morty[0]);
            b = int.Parse(morty[1]);
            for (int i = 0; i < 1000; i++)
            {
                f = a + i * r;
                for (int j = 0; j < 1000; j++)
                {
                    g = b + j * m;
                    if (g == f)
                    {
                        Console.Write(f);
                        goto A;
                    }
                }
            }

            Console.Write(-1);
        A:;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TheMonster
{
    class Program
    {
        static void Main(string[] args)
        {
            //Dados
            string txt = Console.ReadLine();
            int a = int.Parse(txt.Split()[0]), b = int.Parse(txt.Split()[1]);

            txt = Console.ReadLine();
            int c = int.Parse(txt.Split()[0]), d = int.Parse(txt.Split()[1]);

            bool achou = false;
            int resultado = 0;

            for (int i = 0; i < 1000; i++)
            {
                for (int j = 0; j < 1000; j++)
                {
                    if (b + a * i == d + c * j)
                    {
                        resultado = b + a * i;

                        achou = true;
                        break;
                    }
                }
                if (achou)
                    break;
            }
            if (achou)
                Console.Write(resultado);
            else
                Console.Write(-1);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jbjlbjl
{
    class Program
    {
        static void Main(string[] args)
        {
            int f, z;
            string[] asd = Console.ReadLine().Split();
            string[] qwe = Console.ReadLine().Split();
            for(int i = 0; i < 1000; i++)
            {
                f = int.Parse(asd[1]) + i *int.Parse( asd[0]);
                for(int j = 0; j < 1000; j++)
                {
                    z = int.Parse(qwe[1]) + j * int.Parse(qwe[0]);
                    if (z == f) { Console.Write(z);goto a; }
                }
            }
            Console.Write(-1);
        a:;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {

        static void Main(string[] args)
        {
            string[] ss = Console.ReadLine().Split();
            int a = int.Parse(ss[0]);
            int b = int.Parse(ss[1]);
            string[] ss1 = Console.ReadLine().Split();
            int a1 = int.Parse(ss1[0]);
            int b1 = int.Parse(ss1[1]);
            List<ulong> ans1 = new List<ulong>();
            List<ulong> ans2 = new List<ulong>();

             ans1.Add((ulong)b);
             ans2.Add((ulong)b1);
            for (int i = 1; i <= 1000; i++)
            {
                ans1.Add((ulong)(b + (a * i)));
            }
            for (int i = 1; i <= 1000; i++)
            {
                ans2.Add((ulong)(b1 + (a1 * i)));
            }
            /*for (int i = 0; i < ans1.Count; i++)
            {
                Console.Write(ans1[i] + " ");
            }
            Console.WriteLine();

            for (int i = 0; i < ans2.Count; i++)
            {
                Console.Write(ans2[i] + " ");
            }

            Console.WriteLine();*/
            for (int i = 0; i < ans1.Count; i++)
            {
                ulong x = ans1[i];
                for (int e = 0; e < ans2.Count; e++)
                {
                    if (x == ans2[e])
                    {
                        Console.WriteLine(x);
                        return;
                    }
                }
            }
            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Problem7
{
    class Program
    {
        static void Main(string[] args)
        {

            string[] str1 = Console.ReadLine().Split(' ');
            string[] str2 = Console.ReadLine().Split(' ');
            int a =int.Parse(str1[0]);
            int b = int.Parse(str1[1]);
            int c = int.Parse(str2[0]);
            int d = int.Parse(str2[1]);
            int Rick = b;
            int Morty = d;
            int counter = 0;

            lable:
            if (counter < 1000000)
            {
                if (Rick > Morty)
                {
                    while (Rick > Morty)
                    {
                        Morty = Morty + c;
                        counter++;
                        if (Morty >= Rick) { goto lable; }
                    }

                }
                else if (Morty > Rick)
                {
                    while (Morty > Rick)
                    {

                        Rick = Rick + a;
                        counter++;
                        if (Rick >= Morty) { goto lable; }

                    }
                }

                else
                {
                    Console.WriteLine(Rick);
                }
            }
            else
            {
                Console.WriteLine("-1");
            }

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace contest1C
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] ab = Console.ReadLine().Split();
            string[] cd = Console.ReadLine().Split();
            Int64 a = Convert.ToInt64(ab[0]);
            Int64 b = Convert.ToInt64(ab[1]);
            Int64 c = Convert.ToInt64(cd[0]);
            Int64 d = Convert.ToInt64(cd[1]);

            int n1 = 0;
            int n2 = 0;
            Int64 f1 = b + n1 * a;
            Int64 f2 = d + n2 * c;
            for (Int64 i = 0; i < 100; i++)
            {
                for (Int64 j = 0; j < 100; j++)
                {
                    if (b + i * a == d + j * c)
                    {
                        Console.WriteLine(b + i * a);
                        return;
                    }
                }
            }
            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml.Schema;

namespace CodeforcesTasks
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var arr = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var a = arr[0];
            var b = arr[1];
            arr = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var c = arr[0];
            var d = arr[1];

            for (int i = 0; i < 100; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    if (b + a * i == d + c * j)
                    {
                        Console.WriteLine(b + a * i);
                        return;
                    }
                }

            }
            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
class Solve{
    public Solve(){}
    StringBuilder sb;
    public static int Main(){
        new Solve().Run();
        return 0;
    }
    void Run(){
        sb = new StringBuilder();
        Calc();
        Console.Write(sb.ToString());
    }
    void Calc(){
        string[] str = Console.ReadLine().Split(' ');
        int a = int.Parse(str[0]);
        int b = int.Parse(str[1]);
        str = Console.ReadLine().Split(' ');
        int c = int.Parse(str[0]);
        int d = int.Parse(str[1]);
        if((b-d)%gcd(a,c) != 0){
            sb.Append("-1\n");
            return;
        }
        while(b != d){
            if(b < d){
                b += a;
            }
            else{
                d += c;
            }
        }
        sb.Append(b+"\n");
    }
    int gcd(int n,int m){
        if(m == 0){
            return n;
        }
        else{
            return gcd(m,n%m);
        }
    }
}

// Problem: 787A - The Monster
// Author: Gusztav Szmolik

using System;
using System.Collections;

namespace The_Monster
	{
	class Program
		{
		static int Main ()
			{
			string[] tmp = Console.ReadLine().Split();
			if (tmp.Length != 2)
				return -1;
			byte a = 0;
			if (!Byte.TryParse(tmp[0], out a))
				return -1;
			byte b = 0;
			if (!Byte.TryParse(tmp[1], out b))
				return -1;
			if (a < 1 || a > 100 || b < 1 || b > 100)
				return -1;
			tmp = Console.ReadLine().Split();
			if (tmp.Length != 2)
				return -1;
			byte c = 0;
			if (!Byte.TryParse(tmp[0], out c))
				return -1;
			byte d = 0;
			if (!Byte.TryParse(tmp[1], out d))
				return -1;
			if (c < 1 || c > 100 || d < 1 || d > 100)
				return -1;
			byte r;
			byte k = 0;
			ArrayList rList = new ArrayList ();
			bool monsterWins = true;
			do
				{
				r = Convert.ToByte (b < d ? (d-b+c*k)%a : (b-d+a*k)%c);
				if (r != 0 && !rList.Contains(r))
					{
					rList.Add (r);
					k++;
					}
				else if (r != 0 && rList.Contains(r))
					monsterWins = false;
				}
			while (r != 0 && monsterWins);
			if (r == 0)
				Console.WriteLine (b < d ? d+c*k : b+a*k);
			else
				Console.WriteLine (-1);
			return 0;
			}
		}
	}

using System;

namespace CodeForces {
    public class Program {
        public static void Main ( string[] args ) {
            Console.WriteLine( Solve() );
        }

        public static int Solve () {
            var rickMoments = Console.ReadLine().Split(' ');
            var martyMoments = Console.ReadLine().Split(' ');

            int a = int.Parse(rickMoments[0]),
                b = int.Parse(rickMoments[1]),
                c = int.Parse(martyMoments[0]),
                d = int.Parse(martyMoments[1]);

            while ( b != d && b < 100000 ) {
                while ( b > d ) d += c;
                while ( d > b ) b += a;
            }

            return b >= 100000 ? -1 : b;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforced
{
    class A
    {
        static void Main(string[] args)
        {
            string[] token = Console.ReadLine().Split();
            string[] token2 = Console.ReadLine().Split();

            int a = int.Parse(token[0]);
            int b = int.Parse(token[1]);
            int c = int.Parse(token2[0]);
            int d = int.Parse(token2[1]);

            int ans = 0;
            int one = b,two = d;
            List<int> oneList = new List<int>();
            List<int> twoList = new List<int>();

            while(ans<=101)
            {
                one = b + a*ans;
                oneList.Add(one);
                two = d + c*ans;
                twoList.Add(two);
                 ans++;
            }
            bool found = false;
            int aT = -1;
            for(int i=0;i<oneList.Count;i++)
            {
                for(int j=0;j<twoList.Count;j++)
                {
                 if(oneList[i]==twoList[j])
                   {
                    aT = oneList[i];
                    found = true;
                    break;
                   }
                }
                if(found)
                 break;
            }
            Console.WriteLine(aT);

        }
    }
}

using System;

namespace _787A
{
	class Program
	{
		static void Main(string[] args)
		{
			int[] a = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			int[] b = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
			if ((a[1] - b[1]) % GCD(a[0], b[0]) == 0)
			{
				while (a[1] != b[1])
				{
					if (a[1] < b[1])
					{
						a[1] += a[0];
					}
					else
					{
						b[1] += b[0];
					}
				}
				Console.WriteLine(a[1]);
			}
			else
			{
				Console.WriteLine(-1);
			}
		}
		static int GCD(int a, int b)
		{
			int t;
			while (b != 0)
			{
				t = a % b;
				a = b;
				b = t;
			}
			return a;
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zdenkolini
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Upišite prvi broj ");
            var prviRed = Console.ReadLine();
            var drugiRed= Console.ReadLine();
            var a = Convert.ToInt32(prviRed.Split(' ')[0]);

            //Console.WriteLine("Upišite drugi broj ");
            var b = Convert.ToInt32(prviRed.Split(' ')[1]);

            //Console.WriteLine("Upišite treci broj ");
            var c = Convert.ToInt32(drugiRed.Split(' ')[0]);

            //Console.WriteLine("Upišite cetvrti broj ");
            var d = Convert.ToInt32(drugiRed.Split(' ')[1]);

            int g = 0;

            List<Int32> brojevi = new List<Int32>();
            for(int i = 0;  i<1000; i++)
            {

                brojevi.Add(b+a * i);

            }

            List<Int32> brojevi2 = new List<Int32>();
            for (int i = 0; i < 1000; i++)
            {

                brojevi2.Add(d+c * i);

            }

            bool m = true;
            for (int i= 0;i<brojevi.Count; i++)
            {

                for (int t= 0; t < brojevi2.Count; t++)
                {

                        if (brojevi.ElementAt(i) == brojevi2.ElementAt(t))
                        {
                            Console.WriteLine(brojevi.ElementAt(i));
                            m = false;
                        }
                    }

                if (m == false)
                {
                    break;
                }

            }

            if(m == true)
            {
                    Console.WriteLine(-1);
            }

            //foreach (int s in brojevi2)
            //{
            //    Console.Write(s);
            //}

            //foreach (int s in brojevi)
            //{
            //    Console.Write(s);
            //}

            Console.ReadLine();

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test1
{
    public static class Reader
    {
        static List<string> _l = new List<string>();

        static void ReadBuffer()
        {
            if (_l.Count > 0)
                return;
            _l.AddRange(Console.ReadLine().Split(' '));
        }
        public static int ReadInt()
        {
            ReadBuffer();
            int r = int.Parse(_l[0]);
            _l.RemoveAt(0);
            return r;

        }
    }

    class Program
    {

        static void solve()
        {
            int a = 0, b = 0, c = 0, d = 0;

            a = Reader.ReadInt();
            b = Reader.ReadInt();
            c = Reader.ReadInt();
            d = Reader.ReadInt();

            int f1 = 0;
            int f2 = 0;

            int t = 1;
            while (true)
            {
                if (t >= 1000000)
                    break;

                // t = b + a * x
                // x = (t - b) / a;

                if ((((t - b) % a) == 0) &&
                        (((t - d) % c) == 0) && (t >= b) && (t >= d))
                {
                    Console.WriteLine(t);
                    return;
                }
                t++;
            }
            Console.WriteLine(-1);

        }

        static void Main(string[] args)
        {
#if HOMETEST
            for (int i = 0; i < 2; i++)
#endif
            solve();

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]); // a
            s1 = Convert.ToInt32(input[1]); // b
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]); // c
            s2 = Convert.ToInt32(input[1]); // d
            int curr = s2 - s1, y = 0;
            while (curr + f2 * y < 0)
                y++;
            while (y < f1 && (curr + f2 * y) % f1 != 0)
                y++;
            if ((curr + f2 * y) % f1 != 0)
                Console.WriteLine("-1");
            else
                Console.WriteLine(s2 + f2 * y);
        }
    }
}

using System;

namespace C_
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] strArr;
            string str=Console.ReadLine();
            strArr=str.Split(' ');
            int a=Convert.ToInt32(strArr[0]);
            int b=Convert.ToInt32(strArr[1]);
            str=Console.ReadLine();
            strArr=str.Split(' ');
            int c=Convert.ToInt32(strArr[0]);
            int d=Convert.ToInt32(strArr[1]);
            for(int i=0;i<100;i++){
                for(int j=0;j<100;j++){
                    if((a*i)+b==(c*j)+d){
                    Console.WriteLine((a*i)+b);
                    return ;
                    }
                }
            }
            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split();
            int a = Convert.ToInt32(input[0]);
            int b = Convert.ToInt32(input[1]);
            input = Console.ReadLine().Split();
            int c = Convert.ToInt32(input[0]);
            int d = Convert.ToInt32(input[1]);
            bool value = false;
            for (int i = 0; i < 100; i++)
            {
                for (int k = 0; k < 100; k++)
                {
                    if (value == false)
                    {
                        if (b + a * i == d + c * k)
                        {
                            value = true;
                            Console.WriteLine(b + a * i);

                        }
                    }

                }
            }
            if (value == false)
                Console.WriteLine("-1");

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]);
            s1 = Convert.ToInt32(input[1]);
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]);
            s2 = Convert.ToInt32(input[1]);
            if (s1 < s2)
                s1 += (int)Math.Ceiling((s2 - s1) / (double)f1) * f1;
            else
                s2 += (int)Math.Ceiling((s1 - s2) / (double)f2) * f2;
            int i = 0, iterations = f2 / GCD(f1, f2);
            while (s1 % f2 != s2 % f2 && i < iterations)
            {
                s1 += f1;
                i++;
            }
            if (i == iterations)
                Console.WriteLine("-1");
            else
                Console.WriteLine(s1);
        }
        static int GCD(int x, int y)
        {
            while (x != y)
                if (x > y)
                    x -= y;
                else
                    y -= x;
            return x;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a,b,c,d;
            string[] s = Console.ReadLine().Split(' ');

            b = int.Parse(s[0]);
            a = int.Parse(s[1]);

            s = Console.ReadLine().Split(' ');

            d = int.Parse(s[0]);
            c = int.Parse(s[1]);

            int answer = -1;
            for(int i = Math.Max(a,c); i <= 100000; i++)
            {
                if((i-a)%b==0 && (i-c)%d==0)
                {
                    answer = i;
                    break;
                }
            }

            Console.WriteLine(answer);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication22
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] reader = Console.ReadLine().Split(' ');
            int a = int.Parse(reader[0]), b = int.Parse(reader[1]);

            reader = Console.ReadLine().Split(' ');
            int c = int.Parse(reader[0]), d = int.Parse(reader[1]);

            int output = -1;

            var X1 = Enumerable.Range(0, a).Select(x => b + (x * a)).ToList();
            var X2 = Enumerable.Range(0, c).Select(x => d + (x * c)).ToList();
            var mp = new List<int>();

            if (a > c)
            {
                mp = X1.Intersect(X2).ToList();
            }
            else
            {
                mp = X2.Intersect(X1).ToList();
            }
            output = mp.Count > 0 ? mp.First() : -1;
            Console.WriteLine(output);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string,int> Alpha = Enumerable.Range(1, 26).Select(x => Convert.ToChar(64 + x).ToString()).ToDictionary(x=>x , x=>0);
        Alpha["A"] = Alpha["D"] = Alpha["O"] = Alpha["P"] = Alpha["Q"] = Alpha["R"] = 1;
        Alpha["B"] = 2;

        string reader = Console.ReadLine().ToUpper();
        int sum = 0;

        foreach (var item in Alpha)
        {
            Console.WriteLine(item.Key + " => " + item.Value);
        }

        Console.WriteLine(sum);
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace mochila
{
    class Rick
    {
        public int Grito { get; set; }

        public Rick(int grito)
        {
            Grito = grito;
        }
    }

    class Program
    {
        static bool verificaGritos(int a, int b, int c, int d)
        {
            int SomaRick = a + b;
            int SomaMorty = c + d;
            int diferenca = 0;

            if (SomaRick > SomaMorty)
            {
                diferenca = SomaRick - SomaMorty;

                if (diferenca > c)
                    return false;
                else
                    return true;
            }
            else
            {
                diferenca = SomaMorty - SomaRick;

                if (diferenca > a)
                    return false;
                else
                    return true;
            }
        }

        static int comparaComRick(List<Rick> lista, int morty)
        {
            int igual = -1;

            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].Grito == morty)
                {
                    igual = morty;
                }
            }

            return igual;
        }

        static void verificaGritosIguais(int a, int b, int c, int d)
        {
            List<Rick> lista = new List<Rick>();
            int cont = 1, rick = 0, morty = 0, igual = -1;   // Igual j� come�a com -1, caso n�o entre no if, j� sai -1 igual o problema pede

            if (verificaGritos(a, b, c, d))
            {
                do
                {
                    rick = b + (a * cont);        // sequ�ncia de gritos de Rick.
                    morty = c + (d * cont);       // sequ�ncia de gritos de Morty.

                    cont++;                       // contador da sequ�ncia.

                    lista.Add(new Rick(rick));    // Somente o grito do Rick � guardado

                    igual = comparaComRick(lista, morty);   // Vai comparar o grito do morty com os gritos guardados do Rick

                } while (igual != morty);         // Enquanto n�o gritarem ao mesmo tempo

                Console.WriteLine(igual);
            }
            else
            {
                Console.WriteLine(igual);
            }
        }

        static void Main(string[] args)
        {
            string R = Console.ReadLine();
            int a = int.Parse(R.Split()[0]);
            int b = int.Parse(R.Split()[1]);

            string M = Console.ReadLine();
            int c = int.Parse(M.Split()[0]);
            int d = int.Parse(M.Split()[1]);

            verificaGritosIguais(a, b, c, d);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace mochila
{
    class Rick
    {
        public int Grito { get; set; }

        public Rick(int grito)
        {
            Grito = grito;
        }
    }

    class Program
    {
        static bool verificaGritos(int a, int b, int c, int d)
        {
            int SomaRick = a + b;
            int SomaMorty = c + d;
            int diferenca = 0;

            if (SomaRick > SomaMorty)
            {
                diferenca = SomaRick - SomaMorty;

                if (diferenca > c)
                    return false;
                else
                    return true;
            }
            else
            {
                diferenca = SomaMorty - SomaRick;

                if (diferenca > a)
                    return false;
                else
                    return true;
            }
        }

        static int comparaComRick(List<Rick> lista, int morty)
        {
            int igual = -1;

            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].Grito == morty)
                {
                    igual = morty;
                }
            }

            return igual;
        }

        static void verificaGritosIguais(int a, int b, int c, int d)
        {
            List<Rick> lista = new List<Rick>();
            int cont = 1, rick = 0, morty = 0, igual = -1;   // Igual j� come�a com -1, caso n�o entre no if, j� sai -1 igual o problema pede

            if (verificaGritos(a, b, c, d))
            {
                do
                {
                    rick = b + (a * cont);        // sequ�ncia de gritos de Rick.
                    morty = d + (c * cont);       // sequ�ncia de gritos de Morty.

                    cont++;                       // contador da sequ�ncia.

                    lista.Add(new Rick(rick));    // Somente o grito do Rick � guardado

                    igual = comparaComRick(lista, morty);   // Vai comparar o grito do morty com os gritos guardados do Rick

                } while (igual != morty);         // Enquanto n�o gritarem ao mesmo tempo

                Console.WriteLine(igual);
            }
            else
            {
                Console.WriteLine(igual);
            }
        }

        static void Main(string[] args)
        {
            string R = Console.ReadLine();
            int a = int.Parse(R.Split()[0]);
            int b = int.Parse(R.Split()[1]);

            string M = Console.ReadLine();
            int c = int.Parse(M.Split()[0]);
            int d = int.Parse(M.Split()[1]);

            verificaGritosIguais(a, b, c, d);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforced
{
    class A
    {
        static void Main(string[] args)
        {
            string[] token = Console.ReadLine().Split();
            string[] token2 = Console.ReadLine().Split();

            int a = int.Parse(token[0]);
            int b = int.Parse(token[1]);
            int c = int.Parse(token2[0]);
            int d = int.Parse(token2[1]);

            int ans = 0;
            int one = b,two = d;
            List<int> oneList = new List<int>();
            List<int> twoList = new List<int>();

            while(ans<100)
            {
                if(one==two)
                 break;
                one = b + a*ans;
                oneList.Add(one);
                two = d + c*ans;
                twoList.Add(two);
                 ans++;
            }
            bool found = false;
            int aT = -1;
            for(int i=0;i<oneList.Count;i++)
            {
                for(int j=0;j<twoList.Count;j++)
                {
                 if(oneList[i]==twoList[j])
                   {
                    aT = oneList[i];
                    found = true;
                    break;
                   }
                }
                if(found)
                 break;
            }
            Console.WriteLine(aT);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforced
{
    class A
    {
        static void Main(string[] args)
        {
            string[] token = Console.ReadLine().Split();
            string[] token2 = Console.ReadLine().Split();

            int a = int.Parse(token[0]);
            int b = int.Parse(token[1]);
            int c = int.Parse(token2[0]);
            int d = int.Parse(token2[1]);

            int ans = 0;
            int one = b,two = d;
            List<int> oneList = new List<int>();
            List<int> twoList = new List<int>();

            while(ans<=100)
            {
                if(one==two)
                 break;
                one = b + a*ans;
                oneList.Add(one);
                two = d + c*ans;
                twoList.Add(two);
                 ans++;
            }
            bool found = false;
            int aT = -1;
            for(int i=0;i<oneList.Count;i++)
            {
                for(int j=0;j<twoList.Count;j++)
                {
                 if(oneList[i]==twoList[j])
                   {
                    aT = oneList[i];
                    found = true;
                    break;
                   }
                }
                if(found)
                 break;
            }
            Console.WriteLine(aT);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Problem787A
{
    class Program
    {
        static int UCLN(int a, int b)
        {
            int r = a % b;
            if (r != 0)
                return UCLN(b, r);
            else
                return b;
        }
        static void Main(string[] args)
        {
            int a = NextInt(), b = NextInt();
            int c = NextInt(), d = NextInt();
            int flag = 0;
            if (a > c)
                flag = UCLN(a, c);
            else
                flag = UCLN(c, a);
            if ((d - b) % flag != 0)
                Console.Write(-1);
            else
            {
                int x = b + a;
                int y = d + c;
                while (x != y)
                {
                    if (x < y)
                        x += a;
                    else
                        y += c;
                }
                Console.Write(x);
            }
            Console.ReadLine();
        }
        static int s_index = 0;
        static List<string> s_tokens;
        private static string Next()
        {
            while (s_tokens == null || s_index == s_tokens.Count)
            {
                s_tokens = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                s_index = 0;
            }
            return s_tokens[s_index++];
        }
        private static int NextInt()
        {
            return Int32.Parse(Next());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Problem787A
{
    class Program
    {
        static int UCLN(int a, int b)
        {
            int r = a % b;
            if (r != 0)
                return UCLN(b, r);
            else
                return b;
        }
        static void Main(string[] args)
        {
            int a = NextInt(), b = NextInt();
            int c = NextInt(), d = NextInt();
            int flag = 0;
            if (a > c)
                flag = UCLN(a, c);
            else
                flag = UCLN(c, a);
            if (flag != 1)
                Console.Write(-1);
            else
            {
                int x = b + a;
                int y = d + c;
                while (x != y)
                {
                    if (x < y)
                        x += a;
                    else
                        y += c;
                }
                Console.Write(x);
            }
            Console.ReadLine();
        }
        static int s_index = 0;
        static List<string> s_tokens;
        private static string Next()
        {
            while (s_tokens == null || s_index == s_tokens.Count)
            {
                s_tokens = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                s_index = 0;
            }
            return s_tokens[s_index++];
        }
        private static int NextInt()
        {
            return Int32.Parse(Next());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace index
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Ric = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int[] Martin = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int sumRic = Ric[0] + Ric[1];
            int sumMartin = Martin[0] + Martin[1];

            int res = 0;

            if((sumMartin % 2 == 0 && Martin[1] % 2 == 0 && sumRic % 2 != 0 && Ric[1] % 2 != 0) || (sumMartin % 2 != 0 && Martin[1] % 2 != 0 && sumRic % 2 == 0 && Ric[1] % 2 == 0))
            {
                res = -1;
            }
            else
            {
                int M = Martin[1];
                int R = Ric[1];
                int i = 1;
                int j = 1;

                if (M > R)
                {
                    while (R != M)
                    {
                        while (R < M)
                        {
                            R = Ric[1] + Ric[0] * i;
                            i++;
                        }
                        if (R != M)
                        {
                            M = Martin[1] + Martin[0] * j;
                            j++;
                        }
                        if(M > 7000)
                        {
                            res = -1;
                            break;
                        }
                    }
                    if (res != -1)
                    {
                        res = M;
                    }
                }
                else if (R > M)
                {
                    while (R != M && R < 7000)
                    {
                        while (R > M)
                        {
                            M = Martin[1] + Martin[0] * i;
                            i++;
                        }
                        if (R != M)
                        {
                            R = Ric[1] + Ric[0] * j;
                            j++;
                        }
                        if(R > 7000)
                        {
                            res = -1;
                            break;
                        }
                    }
                    if (res != -1)
                    {
                        res = M;
                    }
                }
                else
                {
                    res = M;
                }
            }

            Console.WriteLine(res);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace index
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Ric = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int[] Martin = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int sumRic = Ric[0] + Ric[1];
            int sumMartin = Martin[0] + Martin[1];

            int res = 0;

            if((sumRic % 2 == 0 && sumMartin % 2 == 0) || (sumRic % 2 != 0 && sumMartin % 2 != 0))
            {
                int M = Martin[1];
                int R = Ric[1];
                int i = 1;
                int j = 1;

                if (M > R)
                {
                    while (R != M)
                    {
                        while (R < M)
                        {
                            R = Ric[1] + Ric[0] * i;
                            i++;
                        }
                        M = Martin[1] + Martin[0] * j;
                        j++;
                    }
                    res = M;
                }
                else if(R > M)
                {
                    while (R != M)
                    {
                        while (R > M)
                        {
                            M = Martin[1] + Martin[0] * i;
                            i++;
                        }
                        R = Ric[1] + Ric[0] * j;
                        j++;
                    }
                    res = M;
                }
                else
                {
                    res = M;
                }
            }
            else
            {
                res = -1;
            }

            Console.WriteLine(res);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace index
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Ric = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int[] Martin = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int sumRic = Ric[0] + Ric[1];
            int sumMartin = Martin[0] + Martin[1];

            int res = 0;

            if((sumMartin % 2 == 0 && Martin[1] % 2 == 0 && sumRic % 2 != 0 && Ric[1] % 2 != 0) || (sumMartin % 2 != 0 && Martin[1] % 2 != 0 && sumRic % 2 == 0 && Ric[1] % 2 == 0))
            {
                res = -1;
            }
            else
            {
                int M = Martin[1];
                int R = Ric[1];
                int i = 1;
                int j = 1;

                if (M > R)
                {
                    while (R != M)
                    {
                        while (R < M)
                        {
                            R = Ric[1] + Ric[0] * i;
                            i++;
                        }
                        if (R != M)
                        {
                            M = Martin[1] + Martin[0] * j;
                            j++;
                        }
                    }
                    res = M;
                }
                else if (R > M)
                {
                    while (R != M)
                    {
                        while (R > M)
                        {
                            M = Martin[1] + Martin[0] * i;
                            i++;
                        }
                        R = Ric[1] + Ric[0] * j;
                        j++;
                    }
                    res = M;
                }
                else
                {
                    res = M;
                }
            }

            Console.WriteLine(res);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace index
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Ric = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int[] Martin = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int sumRic = Ric[0] + Ric[1];
            int sumMartin = Martin[0] + Martin[1];

            int res = 0;

            if((sumMartin % 2 == 0 && Martin[1] % 2 == 0 && sumRic % 2 != 0 && Ric[1] % 2 != 0) || (sumMartin % 2 != 0 && Martin[1] % 2 != 0 && sumRic % 2 == 0 && Ric[1] % 2 == 0))
            {
                res = -1;
            }
            else
            {
                int M = Martin[1];
                int R = Ric[1];
                int i = 1;
                int j = 1;

                if (M > R)
                {
                    while (R != M)
                    {
                        while (R < M)
                        {
                            R = Ric[1] + Ric[0] * i;
                            i++;
                        }
                        if (R != M)
                        {
                            M = Martin[1] + Martin[0] * j;
                            j++;
                        }
                        if(M > 7000)
                        {
                            res = -1;
                            break;
                        }
                    }
                    res = M;
                }
                else if (R > M)
                {
                    while (R != M && R < 7000)
                    {
                        while (R > M)
                        {
                            M = Martin[1] + Martin[0] * i;
                            i++;
                        }
                        if (R != M)
                        {
                            R = Ric[1] + Ric[0] * j;
                            j++;
                        }
                        if(R > 7000)
                        {
                            res = -1;
                            break;
                        }
                    }
                    res = M;
                }
                else
                {
                    res = M;
                }
            }

            Console.WriteLine(res);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {

        static void Main(string[] args)
        {
            var s = Console.ReadLine().Split();

            int a = int.Parse(s[0]), b = int.Parse(s[1]);
            s = Console.ReadLine().Split();
            int c = int.Parse(s[0]), d = int.Parse(s[1]);
            for (int i = 1; i <= 10000; i++)
            {
                int x = b + a * i;
                for (int j = 1; j <= 10000; j++)
                {
                    int y = d + j * c;
                    if (x == y)
                    {
                        Console.WriteLine(x);
                        return;
                    }
                }

            }
            Console.WriteLine(-1);

        }

    }
}

using System;

namespace _787A
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input1 = Console.ReadLine().Split(' '), input2 = Console.ReadLine().Split(' ');
            decimal a = decimal.Parse(input1[0]), b = decimal.Parse(input1[1]);
            decimal c = decimal.Parse(input2[0]), d = decimal.Parse(input2[1]);
            bool result = false;
            for (decimal y = 0; y <= 100000; y++)
            {
                decimal x = (d + y * c - b) / a;
                if (x == Math.Floor(x))
                {
                    Console.WriteLine((b + x * a).ToString());
                    result = true;
                    break;
                }
            }
            if (!result) Console.WriteLine("-1");
        }
    }
}

using System;using System.IO;using System.Linq;namespace _100853_Codeforce{    class Program    {        static void Main(string[] args)        {            int[] ric = Console.ReadLine().Split(' ').          Where(x => !string.IsNullOrWhiteSpace(x)).          Select(x => int.Parse(x)).ToArray();            int[] mortey = Console.ReadLine().Split(' ').          Where(x => !string.IsNullOrWhiteSpace(x)).          Select(x => int.Parse(x)).ToArray();            int a = Convert.ToInt32(ric[0]);            int b = Convert.ToInt32(ric[1]);            int c = Convert.ToInt32(mortey[0]);            int d = Convert.ToInt32(mortey[1]);            for(int i = 0; i < 1000000; i++)            {                b += a;                if ((b - d) % c == 0)                {                    Console.WriteLine(b);                    return;                }                            }            Console.WriteLine("-1");        }    }}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Monsters
{
    static void Main()
    {
        List<int> pesho = Console.ReadLine().Split().Select(int.Parse).ToList();
        List<int> gosho = Console.ReadLine().Split().Select(int.Parse).ToList();

        int a = pesho[0];
        int b = pesho[1];
        int c = gosho[0];
        int d = gosho[1];
        Dictionary<int, int> screamers = new Dictionary<int, int>();
        int MaxTime = 100 ^ 2+1;
        int Result = -1;

        for (int i = 1; i < MaxTime; i++)
        {
            if (!screamers.ContainsKey(b + a * i))
            {
                screamers.Add(b + a * i, 1);
            }
            else
            {
                Result = b + a * i;
                break;
            }
            if (!screamers.ContainsKey(d + c * i))
            {
                screamers.Add(d+ c * i, 1);
            }
            else
            {
                Result = d + c * i;
                break;
            }
        }
        Console.WriteLine(Result);
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;

namespace ConsoleApplication1.CodeForces
{
    class _403
    {
        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), Encoding.ASCII, 1024 * 10);

        static void Main(String[] args)
        {
            var a = Next();
            var b = Next();
            var c = Next();
            var d = Next();

            for(var i = 0; i < 100000; i++)
            {
                var dem = a * i + b - d;
                if(dem % c == 0)
                {
                    if (b + (i) * a > 0)
                    {
                        Console.WriteLine(b + (i) * a);
                        return;
                    }
                }
            }

            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;

namespace ConsoleApplication1.CodeForces
{
    class _403
    {
        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), Encoding.ASCII, 1024 * 10);

        static void Main(String[] args)
        {
            var line = reader.ReadLine().Split(' ').Select(int.Parse).ToList();
            var a = line[0];
            var b = line[1];
            line = reader.ReadLine().Split(' ').Select(int.Parse).ToList();
            var c = line[0];
            var d = line[1];

            for(var i = 0; i < 100000; i++)
            {
                var dem = a * i + b - d;
                if(dem % c == 0 && dem > 0)
                {
                        Console.WriteLine(b + (i) * a);
                        return;
                }
            }

            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;

namespace ConsoleApplication1.CodeForces
{
    class _403
    {
        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), Encoding.ASCII, 1024 * 10);

        static void Main(String[] args)
        {
            var a = Next();
            var b = Next();
            var c = Next();
            var d = Next();

            for(var i = 0; i < 100000; i++)
            {
                var dem = a * i + b - d;
                if(dem % c == 0)
                {
                    Console.WriteLine(b + (i)*a);
                    return;
                }
            }

            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;

namespace ConsoleApplication1.CodeForces
{
    class _403
    {
        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024 * 10), Encoding.ASCII, false, 1024 * 10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024 * 10), Encoding.ASCII, 1024 * 10);

        static void Main(String[] args)
        {
            var a = Next();
            var b = Next();
            var c = Next();
            var d = Next();

            for(var i = 0; i < 1000; i++)
            {
                var dem = a * i + b - d;
                if(dem % c == 0)
                {
                    Console.WriteLine(b + (i)*a);
                    return;
                }
            }

            Console.WriteLine(-1);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {

        static void Main(string[] args)
        {
            string[] ss = Console.ReadLine().Split();
            int a = int.Parse(ss[0]);
            int b = int.Parse(ss[1]);
            string[] ss1 = Console.ReadLine().Split();
            int a1 = int.Parse(ss1[0]);
            int b1 = int.Parse(ss1[1]);
            List<ulong> ans1 = new List<ulong>();
            List<ulong> ans2 = new List<ulong>();
            for (int i = 1; i <= 1000; i++)
            {
                ans1.Add((ulong)(b + (a * i)));
            }
            for (int i = 1; i <= 1000; i++)
            {
                ans2.Add((ulong)(b1 + (a1 * i)));
            }
            /*for (int i = 0; i < ans1.Count; i++)
            {
                Console.Write(ans1[i] + " ");
            }
            Console.WriteLine();

            for (int i = 0; i < ans2.Count; i++)
            {
                Console.Write(ans2[i] + " ");
            }

            Console.WriteLine();*/
            for (int i = 0; i < ans1.Count; i++)
            {
                ulong x = ans1[i];
                for (int e = 0; e < ans2.Count; e++)
                {
                    if (x == ans2[e])
                    {
                        Console.WriteLine(x);
                        return;
                    }
                }
            }
            Console.WriteLine(-1);
        }
    }
}

using System;

namespace CodeForces {
    public class Program {
        public static void Main ( string[] args ) {
            Console.WriteLine( Solve() );
        }

        public static int Solve () {
            var rickMoments = Console.ReadLine().Split(' ');
            var martyMoments = Console.ReadLine().Split(' ');

            int a = int.Parse(rickMoments[0]),
                b = int.Parse(rickMoments[1]),
                c = int.Parse(martyMoments[0]),
                d = int.Parse(martyMoments[1]);

            if ( b == d )
                return b;

            if ( (b % 2 == 0 && d % 2 != 0 || b % 2 != 0 && d % 2 == 0)
                 && a % 2 == 0 && c % 2 == 0
                 || b != d && (a % c == 0 || c % a == 0) ) return -1;

            while ( b != d && b < 100000 ) {
                while ( b > d ) d += c;
                while ( d > b ) b += a;
            }

            return b >= 100000 ? -1 : b;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test1
{
    public static class Reader
    {
        static List<string> _l = new List<string>();

        static void ReadBuffer()
        {
            if (_l.Count > 0)
                return;
            _l.AddRange(Console.ReadLine().Split(' '));
        }
        public static int ReadInt()
        {
            ReadBuffer();
            int r = int.Parse(_l[0]);
            _l.RemoveAt(0);
            return r;

        }
    }

    class Program
    {

        static void solve()
        {
            int a = 0, b = 0, c = 0, d = 0;

            a = Reader.ReadInt();
            b = Reader.ReadInt();
            c = Reader.ReadInt();
            d = Reader.ReadInt();

            int f1 = 0;
            int f2 = 0;

            int t = 1;
            while (true)
            {
                if (t >= 1000000)
                    break;

                // t = b + a * x
                // x = (t - b) / a;

                if ((((t - b) % a) == 0) &&
                        (((t - d) % c) == 0))
                {
                    Console.WriteLine(t);
                    return;
                }
                t++;
            }
            Console.WriteLine(-1);

        }

        static void Main(string[] args)
        {
#if HOMETEST
            for (int i = 0; i < 2; i++)
#endif
            solve();

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]);
            s1 = Convert.ToInt32(input[1]);
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]);
            s2 = Convert.ToInt32(input[1]);
            if (s1 < s2)
                s1 += (int)Math.Ceiling(s2 - s1 / (double)f1) * f1;
            else
                s2 += (int)Math.Ceiling(s1 - s2 / (double)f2) * f2;
            int i = 0, iterations = f2 / GCD(f1, f2);
            while (s1 % f2 != s2 % f2 && i < iterations)
            {
                s1 += f1;
                i++;
            }
            if (i == iterations)
                Console.WriteLine("-1");
            else
                Console.WriteLine(s1);
        }
        static int GCD(int x, int y)
        {
            while (x != y)
                if (x > y)
                    x -= y;
                else
                    y -= x;
            return x;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]); // a
            s1 = Convert.ToInt32(input[1]); // b
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]); // c
            s2 = Convert.ToInt32(input[1]); // d
            int curr = s2 - s1;
            int y = curr / f2 * -1 + 1;
            curr += y * f2;
            while (y < f1 && (curr + f2 * y) % f1 != 0)
                y++;
            if ((curr + f2 * y) % f1 != 0)
                Console.WriteLine("-1");
            else
                Console.WriteLine(s2 + f2 * y);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]);
            s1 = Convert.ToInt32(input[1]);
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]);
            s2 = Convert.ToInt32(input[1]);
            int i = 0, iterations = f2 / GCD(f1, f2);
            while (s1 % f2 != s2 % f2 && i < iterations)
            {
                s1 += f1;
                i++;
            }
            if (i == iterations)
                Console.WriteLine("-1");
            else
                Console.WriteLine(s1);
        }
        static int GCD(int x, int y)
        {
            while (x != y)
                if (x > y)
                    x -= y;
                else
                    y -= x;
            return x;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]); // a
            s1 = Convert.ToInt32(input[1]); // b
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]); // c
            s2 = Convert.ToInt32(input[1]); // d
            int curr = s2 - s1, y = 0;
            while (y < f1 && curr + f2 * y >= 0 && (curr + f2 * y) % f1 != 0)
                y++;
            if ((curr + f2 * y) % f1 != 0)
                Console.WriteLine("-1");
            else
                Console.WriteLine(s2 + f2 * y);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]);
            s1 = Convert.ToInt32(input[1]);
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]);
            s2 = Convert.ToInt32(input[1]);
            int target = (s2 - s1) % f2, toAdd = s1, jump = f1 % f2, i = 0;
            if (jump == 0)
            {
                Console.WriteLine(f1);
                return;
            }
            while (i < jump && target % jump != 0)
            {
                target += f2;
                i++;
            }
            if (i == jump)
                Console.WriteLine("-1");
            else
                Console.WriteLine((target / jump) * f1 + toAdd);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]);
            s1 = Convert.ToInt32(input[1]);
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]);
            s2 = Convert.ToInt32(input[1]);
            int target = (s2 - s1) % f2, toAdd = s1, jump = f1 % f2, i = 0;
            while (i < jump && target % jump != 0)
            {
                target += f2;
                i++;
            }
            if (i == jump)
                Console.WriteLine("-1");
            else
                Console.WriteLine((target / jump) * f1 + toAdd);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace The_Monster
{
    class Program
    {
        static void Main(string[] args)
        {
            int s1, f1, s2, f2;
            string[] input = Console.ReadLine().Split(' ');
            f1 = Convert.ToInt32(input[0]); // a
            s1 = Convert.ToInt32(input[1]); // b
            input = Console.ReadLine().Split(' ');
            f2 = Convert.ToInt32(input[0]); // c
            s2 = Convert.ToInt32(input[1]); // d
            int curr = s2 - s1, y = 0;
            while (y < f1 && (curr + f2 * y) % f1 != 0)
                y++;
            if (y == f1)
                Console.WriteLine("-1");
            else
                Console.WriteLine(s2 + f2 * y);
        }
    }
}