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: Accepted)

#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::stdin;

mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;

    #[allow(dead_code)]
    pub fn line() -> String {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    }

    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }
}

#[allow(unused_macros)]
macro_rules! get {
    ($t:ty) => {
        {
            let mut line: String = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t:ty),*) => {
        {
            let mut line: String = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                $(iter.next().unwrap().parse::<$t>().unwrap(),)*
            )
        }
    };
    ($t:ty; $n:expr) => {
        (0..$n).map(|_|
                    get!($t)
                   ).collect::<Vec<_>>()
    };
    ($($t:ty),*; $n:expr) => {
        (0..$n).map(|_|
                    get!($($t),*)
                   ).collect::<Vec<_>>()
    };
    ($t:ty ;;) => {
        {
            let mut line: String = String::new();
            stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|t| t.parse::<$t>().unwrap())
                .collect::<Vec<_>>()
        }
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

struct SEG<T: Clone, F: Fn(&T, &T) -> T> {
    n: usize,
    buf: Vec<T>,
    reducer: F,
}

impl<T: Clone, F: Fn(&T, &T) -> T> SEG<T, F> {
    fn new(n: usize, zero: &T, f: F) -> SEG<T, F> {
        let n = (1..)
            .map(|i| 2usize.pow(i as u32))
            .find(|&x| x > n)
            .unwrap();
        SEG {
            n: n,
            buf: vec![zero.clone(); 2 * n],
            reducer: f,
        }
    }

    fn update(&mut self, k: usize, a: T) {
        let mut k = k + self.n - 1;
        self.buf[k] = a;

        while k > 0 {
            k = (k - 1) / 2;
            self.buf[k] = (self.reducer)(&self.buf[k * 2 + 1], &self.buf[k * 2 + 2]);
        }
    }

    fn add(&mut self, k: usize, a: &T) {
        let mut k = k + self.n - 1;
        self.buf[k] = (self.reducer)(&self.buf[k], a);

        while k > 0 {
            k = (k - 1) / 2;
            self.buf[k] = (self.reducer)(&self.buf[k * 2 + 1], &self.buf[k * 2 + 2]);
        }
    }

    fn q(&self, a: usize, b: usize, k: usize, l: usize, r: usize) -> Option<T> {
        if r <= a || b <= l {
            return None;
        }

        if a <= l && r <= b {
            Some(self.buf[k].clone())
        } else {
            let vl = self.q(a, b, k * 2 + 1, l, (l + r) / 2);
            let vr = self.q(a, b, k * 2 + 2, (l + r) / 2, r);

            match (vl, vr) {
                (Some(l), Some(r)) => Some((self.reducer)(&l, &r)),
                (Some(l), None) => Some(l),
                (None, Some(r)) => Some(r),
                _ => None,
            }
        }
    }

    fn query(&self, a: usize, b: usize) -> T {
        self.q(a, b, 0, 0, self.n).unwrap()
    }
}

fn main() {
    let mut primes = vec![2];

    while primes.last().cloned().unwrap() < 100000 {
        let last = primes.last().cloned().unwrap();

        for x in last + 1.. {
            if primes
                .iter()
                .take_while(|&&d| d * d <= x)
                .all(|&d| x % d != 0)
            {
                primes.push(x);
                break;
            }
        }
    }

    let mut seg = SEG::new(100001, &0, |&a, &b| a + b);

    for n in 1..100000 {
        if primes.binary_search(&n).is_ok() && primes.binary_search(&((n + 1) / 2)).is_ok() {
            seg.add(n, &1);
        }
    }

    let q = get!(usize);

    for _ in 0..q {
        let (l, r) = get!(usize, usize);

        println!("{}", seg.query(l, r + 1));
    }
}