import core.bitop, std.algorithm, std.ascii, std.bigint, std.conv, std.math,
    std.functional, std.numeric, std.range, std.stdio, std.string, std.random,
    std.typecons, std.container, std.format;

// dfmt off
T lread(T = long)(){return readln.chomp.to!T();}
T[] aryread(T = long)(){return readln.split.to!(T[])();}
void scan(TList...)(ref TList Args){auto line = readln.split();
foreach (i, T; TList){T val = line[i].to!(T);Args[i] = val;}}
alias sread = () => readln.chomp();enum MOD = 10 ^^ 9 + 7;
// dfmt on

void main()
{
    immutable MAX = 10 ^^ 5;
    auto S = new long[](MAX + 2);
    {
        auto sieve = new bool[](MAX + 1);
        sieve[] = true;
        sieve[0] = sieve[1] = false;
        foreach (i; 2 .. MAX + 1)
            if (sieve[i])
            {
                foreach (j; 2 .. MAX)
                    if (i * j < sieve.length)
                    {
                        sieve[i * j] = false;
                    }
                    else
                    {
                        break;
                    }
            }
        auto is2017 = new bool[](MAX + 1);
        foreach (i; 3 .. MAX + 1)
            if (i & 1)
            {
                is2017[i] = sieve[i] && sieve[(i + 1) / 2];
            }
        // is2017.take(20).writeln();
        foreach (i; 1 .. MAX + 1)
        {
            S[i] = S[i - 1] + is2017[i];
        }
        S[MAX + 1] = S[MAX];
        // S.take(20).writeln();
    }

    long Q = lread();
    foreach (_; 0 .. Q)
    {
        long l, r;
        scan(l, r);
        writeln(S[r] - S[l - 1]);
    }
}
