Passing the Baton Around the Table

easy math number-theory 1000 ms · 256 MB

Passing the Baton Around the Table

At the end of a long banquet, the hosts play a party game. n guests sit around a round table on seats numbered 1 to n clockwise; seat n is followed by seat 1 again. Every seat is occupied by exactly one guest.

The guest on seat 1 starts with a baton. From then on, whoever holds the baton passes it on, always by the same rule: starting from their own seat, count exactly k seats clockwise, one seat per step, and hand the baton to the guest sitting on the seat where the count stops. The count may go all the way around the table, even several times, and if it stops on the holder's own seat, the holder simply keeps the baton for that pass.

The game never ends: the baton is passed forever. The hosts want to know how many different guests will hold the baton at least once, counting the guest on seat 1, who holds it at the start.

They ask this for t different table sizes and passing rules, each game independent of the others.

Input

The first line contains an integer t (1 ≤ t ≤ 10^5), the number of games.

Each of the next t lines contains two integers n and k (1 ≤ n ≤ 10^18, 1 ≤ k ≤ 10^18): the number of seats and the number of seats the baton moves on each pass.

Output

For each game, print one line with a single integer: the number of different guests who ever hold the baton.

Notes

In the first game of the first example, n = 6 and k = 4: the baton goes from seat 1 to seats 5, 3, 1, 5, 3, … so only the guests on seats 1, 3 and 5 ever hold it, and the answer is 3.

In the third game of the first example, k = 8 takes the baton exactly twice around a table of 4 seats, so it always comes back to the guest on seat 1, and the answer is 1.

The numbers in a single game can be as large as 10^18, so passing the baton one step at a time is far too slow.

Example 1

Input

3
6 4
5 2
4 8

Output

3
5
1

Example 2

Input

3
1 1
12 9
1000000000000000000 999999999999999999

Output

1
4
1000000000000000000

Hints · reveal one at a time if you're stuck

Hint 1

Number the seats from 0. After j passes, which seat holds the baton, as a function of j? Try a small table, such as 6 seats with a step of 4, and see which seats ever repeat.

Hint 2

The seats the baton visits are evenly spaced around the table, and the spacing is the largest step size that divides both the table size and the passing rule. Work out how many seats that leaves, and compute the divisor quickly for numbers up to 10^18.

report an issue Prefer your own editor? sooks prep 23 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.