Rax will randomly provide you a range [ L , R ] (both inclusive) and you have to tell him the maximum difference between the prime numbers in the given range. There are three answers possible for the given range.
There is only one distinct prime number in the given range. The maximum difference in this case would be 0.
There are no prime numbers in the given range. The output for this case would be -1.
To win the game, the participant should answer the prime difference correctly for the given range.
Range: [ 1, 10 ]
The maximum difference between the prime numbers in the given range is 5.
Difference = 7 - 2 = 5
Range: [ 5, 5 ]
There is only one distinct prime number so the maximum difference would be 0.
Range: [ 8 , 10 ]
There is no prime number in the given range so the output for the given range would be -1.
Can you win the game?
The first line of input consists of the number of test cases, T
Next T lines each consists of two space-separated integers, L and R
1<= T <=10
2<= L<= R<=10^6
For each test case, print the maximum difference in the given range in a separate line.
Input
5
5 5
2 7
8 10
10 20
4 5
0
5
-1
8
0
Test Case 1: [ 5 - 5 ] = 0
Test Case 2: [ 7 - 2 ] = 5
Test Case 3: No prime number in the given range. Output = -1
Test Case 4: [ 19 – 11 ] = 8
Test Case 5: The difference would be 0 since there is only one prime number in the given range.
namespace ConsoleApplication1
{
class PrimeGame
{
public static void Main()
{
int T = Convert.ToInt16(Console.ReadLine());
int[] Result = new int[T];
for (int a = 0; a < T; a++)
{
int[] LR = Array.ConvertAll(Console.ReadLine().Trim().Split(' '), arrTemp => int.Parse(arrTemp));
Result[a] = CheckDifference(LR[0], LR[1]);
}
for (int b = 0; b < T; b++)
{
Console.WriteLine(Result[b]);
}
Console.Read();
}
static int CheckDifference(int m, int n)
{
int FN = 0;
int LN = 0;
bool[] prime = new bool[n + 1];
for (int i = 0; i < n + 1; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
for (int i = m; i <= n; i++)
{
if (prime[i] == true)
{
if (FN == 0)
FN = i;
else
LN = i;
}
}
if (FN > 0 && LN == 0)
{
return 0;
}
else if (FN > 0 && LN > 0)
{
return LN - FN;
}
else
{
return -1;
}
}
}
}