PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GL0000278. Quái vật truy đuổi (The Monster)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Quái vật truy đuổi (The Monster)

The Monster

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Rick screams at times b,b+a,b+2a,…b,b+a,b+2a,\ldots, while Morty screams at d,d+c,d+2c,…d,d+c,d+2c,\ldots. All four parameters are positive integers. Find the earliest time that belongs to both sequences, or print -1 if none exists.

Input

Line 1: integers a,ba,b, Rick's interval and first scream time.

Line 2: integers c,dc,d, Morty's corresponding parameters.

Output

One integer: the earliest common time, or -1 if it does not exist.

Subtasks

  • Subtask 1 (20 points): 1≤a,b,c,d≤101\le a,b,c,d\le 10.
  • Subtask 2 (30 points): 1≤a,b,c,d≤401\le a,b,c,d\le 40.
  • Subtask 3 (50 points): 1≤a,b,c,d≤1001\le a,b,c,d\le 100.

Examples

Example 1

Input

20 2
9 19

Output

82

Explanation

Rick starts at 2 and repeats every 20; Morty starts at 19 and repeats every 9. The earliest common time is 82, satisfying both progressions.

Example 2

Input

2 1
16 12

Output

-1

Explanation

Rick starts at 1 and repeats every 2; Morty starts at 12 and repeats every 16. The start-time difference 11 is not divisible by gcd(2,16)=2, so no common time exists.