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 Rust (1.15.1) (judge verdict: Time Limit Exceeded)

extern crate core;

use std::io::{self, Read};

fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let output = run(input.trim().to_string());
    println!("{}", output);
}

fn run(input: String) -> String {
    let list = input.split("\n").skip(1).map(|line| {
        let ll = line.split_whitespace()
            .map(|x| x.parse::<usize>().unwrap())
            .collect::<Vec<_>>();
        //l,r
        (ll[0], ll[1])
    });

    let primes = generate_prime(100000);
    let mut is_prime = Vec::with_capacity(100001);
    for prime in primes {
        for _ in 0..prime - is_prime.len() {
            is_prime.push(false);
        }
        is_prime.push(true);
    }

    for _ in 0..100 {
        is_prime.push(false);
    }

    list.map(|(l, r)| {
        (l..r + 1)
            .filter(|&n| is_prime[n] && is_prime[(n + 1) / 2])
            .count()
            .to_string()
    }).collect::<Vec<_>>()
        .join("\n")
}

fn generate_prime(max: usize) -> Vec<usize> {
    let sqrt_max = (max as f64).sqrt();
    let mut prime_list = Vec::new();

    let mut search_list = (2..max + 1).collect::<Vec<_>>();

    while {
        let prime = search_list[0];
        prime_list.push(prime);
        search_list = search_list.into_iter().filter(|n| n % prime != 0).collect();

        (prime as f64) < sqrt_max
    } {}

    prime_list.append(&mut search_list);

    prime_list
}

#[test]
fn test() {
    let tests = vec![
        ("1\n3 7", "2"),
        ("4\n13 13\n7 11\n7 11\n2017 2017", "1\n0\n0\n1"),
        (
            "6\n1 53\n13 91\n37 55\n19 51\n73 91\n13 49",
            "4\n4\n1\n1\n1\n2",
        ),
    ];
    for (i, (input, output)) in tests.into_iter().enumerate() {
        println!("test:{}", i);
        assert_eq!(run(input.to_string()), output.to_string());
    }
}