Problem:
Score : 400 points

Problem Statement

We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.

You are given Q queries.

In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.

Constraints

1≤Q≤10^5

1≤l_i≤r_i≤10^5

l_i and r_i are odd.

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line (1≤i≤Q) should contain the response to the i-th query.

Sample Input 1

1
3 7

Sample Output 1

2

3 is similar to 2017, since both 3 and (3+1)/2=2 are prime.

5 is similar to 2017, since both 5 and (5+1)/2=3 are prime.

7 is not similar to 2017, since (7+1)/2=4 is not prime, although 7 is prime.

Thus, the response to the first query should be 2.

Sample Input 2

4
13 13
7 11
7 11
2017 2017

Sample Output 2

1
0
0
1

Note that 2017 is also similar to 2017.

Sample Input 3

6
1 53
13 91
37 55
19 51
73 91
13 49

Sample Output 3

4
4
1
1
1
2

Solution in C# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace ABC084D
{
    class Program
    {
        static void Solve(Input input)
        {
            var q = input.NextInt();
            var primes = Prime.PrimeSieve((int)1e5 + 1);
            var similar2017 = new int[(int)1e5 + 1];

            // i+=2しても良いけれど、便宜上偶数も求める
            for (int i = 3; i < similar2017.Length; i++)
            {
                similar2017[i] = similar2017[i - 1];
                if (primes[i] && primes[(i + 1) / 2])
                {
                    similar2017[i]++;
                }
            }

            for (int i = 0; i < q; i++)
            {
                var l = input.NextInt();
                var r = input.NextInt();

                Console.WriteLine(similar2017[r] - similar2017[l - 1]);
            }
        }

        /// <summary>
        /// 素数判定
        /// 素因数分解
        /// 素数列挙（エラトステネスの篩）
        /// 約数列挙
        /// </summary>
        static class Prime
        {
            /// <summary>
            /// 素数か
            /// </summary>
            /// <param name="x"></param>
            /// <returns></returns>
            public static bool IsPrime(long x)
            {
                if (x < 2)
                {
                    return false;
                }
                if (x == 2)
                {
                    return true;
                }
                if ((x % 2) == 0)
                {
                    return false;
                }

                long rx = (long)(Math.Sqrt(x) + 1);
                for (long n = 3; n < rx; n += 2)
                {
                    if ((x % n) == 0)
                    {
                        return false;
                    }
                }

                return true;
            }

            /// <summary>
            /// 素数判定リスト
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public static bool[] PrimeSieve(int n)
            {
                // Sieve of Eratosthenes
                var sieve = Enumerable.Repeat<bool>(true, n + 1).ToArray();

                if (n > 2)
                {
                    sieve[0] = sieve[1] = false;
                }

                var rn = (int)(Math.Sqrt(n) + 1);
                foreach (var i in Enumerable.Range(2, rn - 2))
                {
                    if (sieve[i])
                    {
                        for (int j = 2 * i; j <= n; j += i)
                        {
                            sieve[j] = false;
                        }
                    }
                }

                return sieve;
            }

            /// <summary>
            /// 素数リスト
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public static IEnumerable<int> PrimeList(int n)
            {
                var sieve = PrimeSieve(n);

                return sieve.Select((x, i) => new { X = x, I = i })
                    .Where(x => x.X)
                    .Select(x => x.I);
            }

            /// <summary>
            /// 素因数分解
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public static IEnumerable<long> PrimeFactors(long n)
            {
                var m = n;
                var m2 = (long)Math.Sqrt(m) + 1;
                var p = 2;

                while (p < m2)
                {
                    if ((m % p) == 0)
                    {
                        m = m / p;
                        m2 = (long)Math.Sqrt(m) + 1;
                        yield return p;
                    }
                    else
                    {
                        p++;
                    }
                }
                if (m > 1)
                {
                    yield return m;
                }
            }

            /// <summary>
            /// n以下でnと互いに素な数の個数
            /// オイラーのファイ関数
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public static long PrimeCount(long n)
            {
                var primes = PrimeFactors(n).Distinct();

                var dsum = new decimal(1);
                foreach (var p in primes)
                {
                    var pp = new decimal(p);

                    dsum *= 1 - (1 / pp);
                }

                return (long)Math.Round(dsum * n);
            }

            /// <summary>
            /// 約数列挙 順番はバラバラなので注意！
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public static IEnumerable<long> Divisors(long n)
            {
                if (n < 1)
                {
                    yield break;
                }

                var rn = (int)(Math.Sqrt(n) + 1);
                for (long i = 1; i < rn; i++)
                {
                    if ((n % i) == 0)
                    {
                        yield return i;

                        if (i != (n / i))
                        {
                            yield return n / i;
                        }
                    }
                }
            }

            /// <summary>
            /// 約数列挙 昇順にソート
            /// </summary>
            /// <param name="n"></param>
            /// <param name="needsSort"></param>
            /// <returns></returns>
            public static IEnumerable<long> Divisors(long n, bool needsSort)
            {
                var divs = Divisors(n);

                if (needsSort)
                {
                    return divs.OrderBy(x => x);
                }
                else
                {
                    return divs;
                }
            }
        }

        #region Competitive Template
        static readonly int MOD = (int)1e9 + 7;

        public static void Main(string[] args)
        {
            // 出力が少ないときはこれをセットする方が時間かかるけれど
            // その場合は出力がボトルネックになっていないので、まあ良しとする
            var needsFlushOutput = true;
            if (needsFlushOutput)
            {
                // 細かく出力しないようにする
                var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
                Console.SetOut(sw);
            }

            // 通常は引数無しで、ファイルから読み出したい場合はpath指定する
            var input = new Input();
            // 仮想的に標準入力をセットする
            //input.SetText("");

            Solve(input);

            Console.Out.Flush();
        }

        class Input
        {
            // 変な改行コードがたまに混じっているので、一応セパレート指定する
            // スペース単独指定の方がもちろん早い
            static readonly char[] separator = { ' ', '\r', '\n' };
            Queue<string> q { get; set; }
            StreamReader sr;

            /// <summary>
            /// 特定のファイルから読み出したい場合はpath指定する
            /// </summary>
            /// <param name="path"></param>
            public Input(string path = "")
            {
                q = new Queue<string>();

                if (string.IsNullOrEmpty(path))
                {
                    sr = new StreamReader(Console.OpenStandardInput());
                }
                else
                {
                    sr = new StreamReader(path);
                }
            }

            /// <summary>
            /// 入力予約
            /// </summary>
            /// <param name="items"></param>
            public void SetText(IEnumerable<string> items)
            {
                foreach (var item in items)
                {
                    SetText(item);
                }
            }

            /// <summary>
            /// 入力予約
            /// </summary>
            /// <param name="s"></param>
            /// <returns></returns>
            public bool SetText(string s)
            {
                if (s == null) return false;

                foreach (var elem in s.Trim().Split(separator, StringSplitOptions.RemoveEmptyEntries))
                {
                    q.Enqueue(elem);
                }

                return true;
            }

            /// <summary>
            /// 内部queueに入力からの値をsplitして格納する
            /// </summary>
            /// <returns></returns>
            bool read()
            {
                var s = sr.ReadLine();
                if (s == null) return false;

                foreach (var elem in s.Trim().Split(separator, StringSplitOptions.RemoveEmptyEntries))
                {
                    q.Enqueue(elem);
                }

                if (!q.Any()) return read();

                return true;
            }

            /// <summary>
            /// 次のstringを一つ読み込む
            /// </summary>
            /// <returns></returns>
            public string Next()
            {
                if (!q.Any())
                {
                    if (!read())
                    {
                        return "";
                    }
                }

                return q.Dequeue();
            }

            /// <summary>
            /// 指定個数queueにたまるまでenqueueし続ける
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            bool accumulate(int n)
            {
                while (q.Count() < n)
                {
                    if (!read()) return false;
                }

                return true;
            }

            public int NextInt() => int.Parse(Next());
            public long NextLong() => long.Parse(Next());
            public double NextDouble() => double.Parse(Next());

            /// <summary>
            /// n個の要素をparseして、それぞれにoffsetをaddした配列を返す
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="n"></param>
            /// <param name="offset"></param>
            /// <param name="parse"></param>
            /// <param name="add"></param>
            /// <returns></returns>
            T[] NextT<T>(int n, T offset, Func<string, T> parse, Func<T, T, T> add)
            {
                if (!accumulate(n)) return null;

                var a = new T[n];

                for (int i = 0; i < n; i++)
                    a[i] = add(parse(q.Dequeue()), offset);

                return a;
            }

            public string[] Next(int n) => NextT(n, "", x => x, (x, y) => x);
            public int[] NextInt(int n, int offset = 0) => NextT(n, offset, int.Parse, (x, y) => x + y);
            public long[] NextLong(int n, long offset = 0) => NextT(n, offset, long.Parse, (x, y) => x + y);
            public double[] NextDouble(int n, double offset = 0.0) => NextT(n, offset, double.Parse, (x, y) => x + y);
        }

        static class Utils
        {
            public static void Print<T>(IEnumerable<T> ie, string sep = " ") => Console.WriteLine(string.Join(sep, ie));
            public static void Print<T>(params T[] objs) => Print(objs);
            public static T Max<T>(params T[] objs) => objs.Max();
            public static T Min<T>(params T[] objs) => objs.Min();

            public static void Swap<T>(ref T x, ref T y) where T : struct { var t = x; x = y; y = t; }
            public static void Swap<T>(IList<T> list, int i, int j) where T : struct { var t = list[i]; list[i] = list[j]; list[j] = t; }

            /// <summary>
            /// vでfillされたT[d1][d2]配列を作成する
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="d1"></param>
            /// <param name="d2"></param>
            /// <param name="v"></param>
            /// <returns></returns>
            public static T[][] Create2DArray<T>(int d1, int d2, T v = default(T))
            {
                return
                    Enumerable.Repeat(0, d1).Select(_ =>
                    Enumerable.Repeat(v, d2).ToArray()).ToArray();
            }

            /// <summary>
            /// vでfillされたT[d1][d2][d3]配列を作成する
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="d1"></param>
            /// <param name="d2"></param>
            /// <param name="d3"></param>
            /// <param name="v"></param>
            /// <returns></returns>
            public static T[][][] Create3DArray<T>(int d1, int d2, int d3, T v = default(T))
            {
                return
                    Enumerable.Repeat(0, d1).Select(_ =>
                    Enumerable.Repeat(0, d2).Select(__ =>
                     Enumerable.Repeat(v, d3).ToArray()).ToArray()).ToArray();
            }
        }
        #endregion
    }
}