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

#GL0000294. Giá trị nhỏ nhất của biểu thức dư tuyến tính (Min of Mod of Linear)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Giá trị nhỏ nhất của biểu thức dư tuyến tính (Min of Mod of Linear)

Min of Mod of Linear

Source: Library Checker

Version: Phuoc Hung OJ Extended

Problem Statement

Given four integers N,M,A,BN,M,A,B, consider the least nonnegative residues of Ai+BAi+B modulo MM for all integer indices 0≤i<N0\le i<N. Find the minimum of these residues. Every remainder is defined to lie in [0,M−1][0,M-1].

Input

One line containing four integers N,M,A,BN,M,A,B.

Output

Print one integer equal to min⁡0≤i<N((Ai+B) mod M)\min_{0\le i<N}((Ai+B)\bmod M).

Subtasks

  • Subtask 1 (20 points): 1≤N,M≤10001\le N,M\le1000; 0≤A,B<M0\le A,B<M.
  • Subtask 2 (30 points): 1≤N,M≤1061\le N,M\le10^6; 0≤A,B<M0\le A,B<M.
  • Subtask 3 (50 points): 1≤N,M≤1091\le N,M\le10^9; 0≤A,B<M0\le A,B<M.

Examples

Example 1

Input

5 7 3 2

Output

0

Explanation

For i=0,…,4i=0,\ldots,4 the residues are 2, 5, 1, 4, 0. Their minimum is 0.

Example 2

Input

4 9 0 5

Output

5

Explanation

For i=0,…,3i=0,\ldots,3 the residues are 5, 5, 5, 5. Their minimum is 5.

Example 3

Input

6 10 4 1

Output

1

Explanation

For i=0,…,5i=0,\ldots,5 the residues are 1, 5, 9, 3, 7, 1. Their minimum is 1.