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

#GL0000293. Tổng phần nguyên (Floor Sum)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổng phần nguyên (Floor Sum)

Floor Sum

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

You are given four integers N,M,A,BN,M,A,B. For every index ii with 0≤i<N0\le i<N, take the floor of (Ai+B)/M(Ai+B)/M.

Compute the exact integer sum

$$S=\sum_{i=0}^{N-1}\left\lfloor\frac{Ai+B}{M}\right\rfloor.$$

Here ⌊x⌋\lfloor x\rfloor is the largest integer not greater than xx. Do not take the answer modulo any number.

Input

One line containing four integers NN, MM, AA, BB, in that order.

Output

Print one integer SS, the requested sum.

Subtasks

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

Examples

Input

4 10 6 3

Output

3

Explanation

For i=0,1,2,3i=0,1,2,3, the numerators are 3,9,15,213,9,15,21. Dividing by 1010 and taking the floors yields 0,0,1,20,0,1,2. Their sum is 0+0+1+2=30+0+1+2=3.

Input

1000000000 1000000000 999999999 999999999

Output

499999999500000000

Explanation

Since A=B=M−1A=B=M-1 and i<Mi<M, the floor of (Ai+B)/M(Ai+B)/M is ii. Thus the answer is 0+1+⋯+(N−1)=N(N−1)/2=4999999995000000000+1+\cdots+(N-1)=N(N-1)/2=499999999500000000.