Three Days Grace solution codeforces-

Three Days Grace solution codeforces-

Ibti was thinking about a good title for this problem that would fit the round theme (numerus ternarium). He immediately thought about the third derivative, but that was pretty lame so he decided to include the best band in the world — Three Days Grace.

You are given a multiset A with initial size n, whose elements are integers between 11 and m. In one operation, do the following:

  • select a value x from the multiset A, then
  • select two integers p and q such that ,>1p,q>1 and =p⋅q=x. Insert p and q to A, delete x from A.

Note that the size of the multiset A increases by 11 after each operation.

We define the balance of the multiset A as max()min()max(ai)−min(ai). Find the minimum possible balance after performing any number (possible zero) of operations.


The first line of the input contains a single integer t (11051≤t≤105) — the number of test cases.

The second line of each test case contains two integers n and m (11061≤n≤106151061≤m≤5⋅106) — the initial size of the multiset, and the maximum value of an element.

The third line of each test case contains n integers 1,2,,a1,a2,…,an (11≤ai≤m) — the elements in the initial multiset.

It is guaranteed that the sum of n across all test cases does not exceed 106106 and the sum of m across all test cases does not exceed 51065⋅106.


For each test case, print a single integer — the minimum possible balance.



5 10
2 4 2 4 2
3 50
12 2 3
2 40
6 35
2 5
1 5



In the first test case, we can apply the operation on each of the 44s with (,)=(2,2)(p,q)=(2,2) and make the multiset {2,2,2,2,2}{2,2,2,2,2} with balance max({2,2,2,2,2})min({2,2,2,2,2})=0max({2,2,2,2,2})−min({2,2,2,2,2})=0. It is obvious we cannot make this balance less than 00.

In the second test case, we can apply an operation on 1212 with (,)=(3,4)(p,q)=(3,4). After this our multiset will be {3,4,2,3}{3,4,2,3}. We can make one more operation on 44 with (,)=(2,2)(p,q)=(2,2), making the multiset {3,2,2,2,3}{3,2,2,2,3} with balance equal to 11.

In the third test case, we can apply an operation on 3535 with (,)=(5,7)(p,q)=(5,7). The final multiset is {6,5,7}{6,5,7} and has a balance equal to 75=27−5=2.

In the forth test case, we cannot apply any operation, so the balance is 51=45−1=4.

Solution – CLICK HERE

Leave a Comment