E - Simple Math 3 解説 /

実行時間制限: 2 sec / メモリ制限: 1024 MB

配点 : 800

問題文

この問題では一つの入力につきテストケースが T 個与えられます。

整数 A, B, C, D が与えられます。次の条件を満たす正整数 i はいくつあるか求めてください。

  • A + B \times i 以上 A + C \times i 以下の整数はいずれも、D の倍数ではない。

なお、制約より答えが有限であることが証明できます。

制約

  • 1 \leq T \leq 10{,}000
  • 1 \leq A < D
  • 0 \leq B < C < D
  • 2 \leq D \leq 10^8

入力

入力は以下の形式で標準入力から与えられる。

T
A_1 B_1 C_1 D_1
:
A_T B_T C_T D_T

出力

T 行出力せよ。

i 行目には、i ケース目 (A_i, B_i, C_i, D_i) の答えを出力せよ。


入力例 1

2
3 1 2 5
99 101 103 105

出力例 1

1
25

1 ケース目の (A + B \times i, A + C \times i) を列挙すると次のようになります。 i = 3 のみ条件を満たすことがわかります。

  • i = 1: (4, 5)
  • i = 2: (5, 7)
  • i = 3: (6, 9)
  • i = 4: (7, 11)
  • i = 5: (8, 13)
  • :

Score : 800 points

Problem Statement

In this problem, you will be given T test cases for each input.

Given integers A, B, C, and D, find the number of positive integers i satisfying the following condition:

  • None of the integers between A + B \times i and A + C \times i (inclusive) is a multiple of D.

We can prove from the constraints that the count is finite.

Constraints

  • 1 \leq T \leq 10{,}000
  • 1 \leq A < D
  • 0 \leq B < C < D
  • 2 \leq D \leq 10^8

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
:
A_T B_T C_T D_T

Output

Print T lines.

The i-th line should contain the answer for the i-th case (A_i, B_i, C_i, D_i).


Sample Input 1

2
3 1 2 5
99 101 103 105

Sample Output 1

1
25

The pairs (A + B \times i, A + C \times i) for the first case are listed below. We can see that only i = 3 satisfies the condition.

  • i = 1: (4, 5)
  • i = 2: (5, 7)
  • i = 3: (6, 9)
  • i = 4: (7, 11)
  • i = 5: (8, 13)
  • :