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



Sample input:
1
3 7


Sample output:
2

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    from collections import defaultdict
    from math import sqrt
    input = stdin.readline

    h = defaultdict(int)
    h[2] = 1
    for i in range(3, 100000, 2):
        for j in range(3, int(sqrt(i)) + 1, 2):
            while i % j == 0:
                h[j] = 1
                i //= j
        if i > 1:
            h[i] = 1
    k = [0] * 100001
    for key in h.keys():
        if (key + 1) / 2 in h and h[(key + 1) / 2] == 1:
            k[key] = 1
    for i in range(1, 100001):
        k[i] += k[i - 1]
    q = int(input())
    for _ in range(q):
        l, r = map(int, input().split())
        print(k[r] - k[l - 1])
main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc084/tasks/abc084_d

Nmax = 10**5 + 1

def prime_test(n):
    if n == 1:
        return False
    i = 2
    while i*i<=n:
        if n%i:
            i += 1
        else:
            return False
    return True

cum = [0]*Nmax

for n in range(1,Nmax,2):
    cum[n] = cum[n-2] + (prime_test(n) and prime_test((n + 1)/2))

Q = int(input())
for _ in range(Q):
    l, r = map(int, input().split())
    print(cum[r] - cum[l-2])

Submission status: Accepted

Solution code:
def calc_prime(n):
    primes = set(list(range(3, n, 2)))
    primes.add(2)
    for a in range(3, n, 2):
        for i in range(a, n):
            x = a * i
            if x >= n:
                break
            if x in primes:
                primes.remove(x)

    return primes


def collect_likes(ps):
    likes = set([p for p in ps if (p + 1) / 2 in ps])
    return likes


def line(xs, n):
    ps = list(xs)
    ps.sort()
    cs = [0] * n
    s = 0
    for i in range(n):
        if i in xs:
            cs[i] = s
            s += 1
        else:
            cs[i] = s

    return cs


def main():
    n = 10 ** 5 + 9
    primes = calc_prime(n)
    likes = collect_likes(primes)
    cums = line(likes, n)
    #print(sorted(list(primes))[:100])
    #print(sorted(list(likes))[:100])
    #print(cums[:10])

    q = int(input())
    for _ in range(q):
        l, r = [int(x) for x in input().split()]
        ans = cums[r + 1] - cums[l]
        print(ans)


main()

Submission status: Accepted

Solution code:
import numpy as np
def make_prime(U):
    is_prime = np.zeros(U,np.bool)
    is_prime[2] = 1
    is_prime[3::2] = 1
    M = int(U**.5)+1
    for p in range(3,M,2):
        if is_prime[p]:
            is_prime[p*p::p+p] = 0
    return is_prime, is_prime.nonzero()[0]

p=set(make_prime(10**5)[1])
lst=[0]*(10**5+2)
cnt=0
for i in range(100001):
    if i in p and (i+1)//2 in p:
        cnt+=1
    lst[i]=cnt
q=int(input())
for i in range(q):
    l,r=map(int,input().split())
    print(lst[r]-lst[l-1])

Submission status: Accepted

Solution code:
q = int(input())
LR = [0]*q
for i in range(q):
    LR[i] = list(map(int,input().split()))
lis = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317]

p_lis = [0]*(1+10**5)
for i in range(3,10**5+1):
    sw1 = 1
    sw2 = 1
    for P in lis:
        if P > i**0.5:
            break
        if i%P == 0:
            sw1 = 0
            break
        
    if sw1 == 1:
        for P in lis:
            if P > ((i+1)//2)**0.5:
                break
            if (i+1)//2%P == 0:
                sw2 = 0
                break
            
    if sw1 == 1 and sw2 == 1:
        p_lis[i] = 1
s_lis = [0]*(1+10**5)
for i in range(1,len(p_lis)):
    if p_lis[i] == 1:
        s_lis[i] = s_lis[i-1] + 1
    else:
        s_lis[i] = s_lis[i-1]
for L,R in LR:
    print(s_lis[R]-s_lis[L-1])

Submission status: Accepted

Solution code:
def main():
    import math
    def generate_primes(num):
        if num == 1: return []
        primes = list(range(2, num + 1))
        i, p = 0, 1
        while p <= math.sqrt(num):
            if primes[i] != 0:
                p = primes[i]
                primes = [prime if (prime % p != 0 or prime == p) else 0 for prime in primes]
            i += 1
        return set([p for p in primes if p != 0])

    primes = generate_primes(100000)
    ans = [0] * 50001
    for j in range(1, 50001):
        i = 2 * j - 1
        if i in primes and (i + 1) // 2 in primes:
            ans[j] = ans[j - 1] + 1
        else:
            ans[j] = ans[j - 1]
    q = int(input())
    for _ in range(q):
        l, r = list(map(lambda x: (int(x) + 1) // 2, input().split()))
        print(ans[r] - ans[l - 1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

s = [0] * (100001)
for i in range(1, 10**5+1): 
    if i%2 == 1 and is_prime(i) and is_prime((i+1)//2):
        s[i-1] = 1

lst = [0] * (100001)
for i in range(10**5):
    lst[i+1] = lst[i] + s[i]

q = int(input())
for k in range(q):
    l, r = map(int, input().split())
    print(lst[r]-lst[l-1])

Submission status: Accepted

Solution code:
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

def bisect(lst, isok, ok, ng):
    while(abs(ok-ng)>1):
        mid = (ok+ng)//2
        if isok(lst[mid]):
            ok = mid
        else:
            ng = mid
    return ok

s = []
for i in range(10**5):
    if i%2 == 1 and is_prime(i) and is_prime((i+1)//2):
        s.append(i)

s.sort()

q = int(input())
for k in range(q):
    l, r = map(int, input().split())
    l0 = bisect(s, lambda x:x >= l, len(s), -1)
    r0 = bisect(s, lambda x:x <= r, -1, len(s))
    print(max(0, r0-l0+1))

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
from decimal import Decimal

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    # エラトステネスの篩で、
    # 2 から 10^5までの素数を列挙
    limit = 10 ** 5 + 1
    prime = [False if n % 2 == 0 or n % 3 == 0 or n % 5 == 0 else True for n in range(limit)]
    prime[0] = prime[1] = False
    prime[2] = prime[3] = prime[5] = True
    for p in range(3, limit, 2):
        if math.sqrt(limit) < p:
            break
        for q in range(p ** 2, limit, p):
            prime[q] = False

    # 累積和
    # 2017に似た数字の数を求めておく
    cnt = [0] * limit
    for n in range(len(cnt)):
        if prime[n] and prime[(n + 1) // 2]:
            cnt[n] = 1
    for n in range(1, len(cnt)):
        cnt[n] += cnt[n - 1]

    # 回答
    Q = ii()
    for q in range(Q):
        l, r = il()
        print(cnt[r] - cnt[l - 1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import os
import math
import bisect
import collections
import itertools
import heapq
import re
import queue
from decimal import Decimal

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    # エラトステネスの篩で、
    # 2 から 10^5までの素数を列挙
    limit = 10 ** 5 + 1
    prime = [False if n % 2 == 0 or n % 3 == 0 or n % 5 == 0 else True for n in range(limit)]
    prime[0] = prime[1] = False
    prime[2] = prime[3] = prime[5] = True
    for p in range(3, limit, 2):
        if math.sqrt(limit) < p:
            break
        for q in range(p ** 2, limit, p):
            prime[q] = False

    # 累積和
    # 2017に似た数字の数を求めておく
    cnt = [0]*limit
    for n in range(len(cnt)):
        if prime[n] and prime[(n+1)//2]:
            cnt[n] = 1
    for n in range(1, len(cnt)):
        cnt[n] += cnt[n-1]

    # 回答
    Q = ii()
    for q in range(Q):
        l, r = il()
        print(cnt[r]-cnt[l-1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
import bisect
def binary_search(a,n):
    low = 0
    high = len(a) - 1
    while low <= high:
        mid = (low + high) // 2
        index = a[mid]
        if index == n:
            return True
        elif index < n:
            low = mid+1
        else:
            high = mid -1
    return False

def get_sieve_oof_eratosthenes(n):
    prime = []
    limit = math.sqrt(n)
    data = [i + 1 for i in range(1,n)]
    while True:
        p = data[0]
        if limit <= p:
            return prime + data
        prime.append(p)
        data = [e for e in data if e % p != 0]
data = get_sieve_oof_eratosthenes(10**5 + 1)
count = [0 for i in range(10**5+1)]
for i in range(3,10**5,2):
    if binary_search(data,i) and binary_search(data,(i+1)//2):
            count[i] += count[i-1] + 1
            count[i+1] = count[i]
    else:
        count[i] += count[i-1]
        count[i+1] = count[i]
q = int(input())
for i in range(q):
    l,r = map(int,input().split())
    print(count[r]-count[l-1])

Submission status: Accepted

Solution code:
is_prime = [1]*101010
is_prime[0] = 0
is_prime[1] = 0
max = 101010

for i in range(2,max):
    if is_prime[i]:
        j = i*2
        while j <= max-1:
            is_prime[j] = 0
            j += i

a = [0]*max
for i in range(max):
    if(i%2==0): 
        continue
    if(is_prime[i]==1 and is_prime[(i+1)//2]==1):
        a[i]=1

s = [0]*(max+1)
for i in range(max):
    s[i+1] = s[i]+a[i]


q = int(input())
for i in range(q):
    l, r = map(int, input().split())
    r += 1
    
    print(s[r]-s[l])

Submission status: Accepted

Solution code:
import bisect

def sieve(n):
	ret = []
	divlis = [-1]*(n+1)  # 何で割ったかのリスト(初期値は-1)
	flag = [True]*(n+1)
	flag[0] = False
	flag[1] = False
	ind = 2
	while ind <= n:
		if flag[ind]:
			ret.append(ind)
			ind2 = ind**2
			while ind2 <= n:
				flag[ind2] = False
				divlis[ind2] = ind
				ind2 += ind
		ind += 1
	#何で割ったかのリストを取得したいとき, divlisも出力する
	return ret

svl = set(sieve(10**5))
ansl = []

for i in svl:
	if i * 2 - 1 in svl:
		ansl.append(i*2-1)

ansl.sort()

q = int(input())

for _ in range(q):
	l, r = map(int,input().split())
	ans = bisect.bisect_right(ansl, r) - bisect.bisect_left(ansl, l)
	print(ans)

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    q = int(ipt())

    #√nまでの素数の配列を返す関数
    def primes(n):
        if n < 4:
            return []
        else:
            pri = [2]
            k = 3
            while k*k <= n:
                for i in pri:
                    if k%i == 0:
                        break
                    elif i == pri[-1]:
                        pri.append(k)
                k += 2
            return pri

    p = primes(10**10)
    sm = [0]*100001
    for pi in p[1::]:
        if (pi+1)//2 in p:
            sm[pi] += 1

    for i in range(100000):
        sm[i+1] += sm[i]

    for _ in [0]*q:
        l,r = map(int,ipt().split())
        print(sm[r]-sm[l-1])

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
import sys
input = sys.stdin.readline

def prime_boolean_table(n):
    primes = [True] * (n + 1)
    primes[0] = False
    primes[1] = False
    for i in range(2, n + 1):
        if primes[i]:
            for j in range(i + i, n + 1, i):
                primes[j] = False
    return primes

def main():
    pl = prime_boolean_table(10**5)
    ql = [0]*(10**5+1)
    for i in range(1,10**5+1):
        if pl[i] and pl[(i+1)//2]:
            ql[i] += 1
    ql = list(itertools.accumulate(ql))
    q = int(input())
    for _ in range(q):
        l,r = map(int,input().split())
        print(ql[r]-ql[l-1])

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np
input = sys.stdin.buffer.readline
Q = int(input())


def is_prime(v):
    for i in range(2, v):
        if i * i > v:
            break
        if v % i == 0:
            return False
    return True


def make_prime(U):
    is_prime = np.zeros(U, np.bool)
    is_prime[2] = 1
    is_prime[3::2] = 1
    M = int(U**.5) + 1
    for p in range(3, M, 2):
        if is_prime[p]:
            is_prime[p * p::p + p] = 0
    return is_prime


is_primes = make_prime(10**5 + 2)
# print('is_primes', is_primes[:14])

V = [0] * (10**5 + 2)
for i in range(1, len(V)):
    if i % 2 == 0:
        V[i] = V[i - 1]
        continue
    if is_primes[i] and is_primes[(i + 1) // 2]:
        V[i] = V[i - 1] + 1
    else:
        V[i] = V[i - 1]
# print('V', V)

for _ in range(Q):
    l, r = map(int, input().split())
    # print('l - 1, r, V[l- 1], V[r]', l - 1, r, V[l - 1], V[r])
    print(V[r] - V[l - 1])

Submission status: Accepted

Solution code:
import bisect
import sys

input = sys.stdin.readline

# 素因数分解
def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a

def main():
    N = 100001
    prime = []
    for i in range(3, N):
        tmp = prime_factorize(i)
        if len(tmp) == 1:
            prime.append(i)
    
    primes = []
    for p in prime:
        k = (p+1)//2
        tmp = prime_factorize(k)
        if len(tmp) == 1:
            primes.append(p)

    Q = int(input())
    for _ in range(Q):
        l, r = map(int, input().split())
        ans = bisect.bisect_right(primes, r) - bisect.bisect_left(primes, l)
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import math

n = int(input())
a = 0
li = [] #累積和のリスト
ans = []

def is_prime(n):
    if n == 1:
        return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False
    return True

for i in range(10**5//2):
    x = 2*i+1
    y = i+1
    if is_prime(y):
        if is_prime(x):
            a += 1
    li.append(a)

for i in range(n):
    l, r = map(int,input().split())
    ans.append(li[r//2]-li[max(0,l//2-1)])

for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import math


def get_sieve_of_eratosthenes(n):# エラトステネスのふるい(O(NloglogN)). ~nまでの素数をリストで返す.
    if not isinstance(n, int):
        raise TypeError('n is int type.')
    if n < 2:
        raise ValueError('n is more than 2')
    prime = []
    limit = math.sqrt(n)
    data = [i + 1 for i in range(1, n)]
    while True:
        p = data[0]
        if limit <= p:
            return prime + data
        prime.append(p)
        data = [e for e in data if e % p != 0]


Q = int(input())
ls = [0]
prime = set(get_sieve_of_eratosthenes(10**5 + 10))

output = []
for i in range(10**5+10):
    if (i in prime) & (int((i+1)/2) in prime):
        ls.append(ls[-1]+1)
    else: 
        ls.append(ls[-1])

for q in range(Q):
    l, r = map(int, input().split())
    output.append(ls[r+1]-ls[l])
print(*output, sep="\n")

Submission status: Accepted

Solution code:
import math


def get_sieve_of_eratosthenes(n):# エラトステネスのふるい(O(NloglogN)). ~nまでの素数をリストで返す.
    if not isinstance(n, int):
        raise TypeError('n is int type.')
    if n < 2:
        raise ValueError('n is more than 2')
    prime = []
    limit = math.sqrt(n)
    data = [i + 1 for i in range(1, n)]
    while True:
        p = data[0]
        if limit <= p:
            return prime + data
        prime.append(p)
        data = [e for e in data if e % p != 0]


Q = int(input())
ls = [0]
prime = set(get_sieve_of_eratosthenes(10**5 + 10))

output = []
for i in range(1, 10**5+1):
    if (i in prime) & (int((i+1)/2) in prime):
        ls.append(ls[i-1]+1)
    else: ls.append(ls[i-1])
#print(ls[:10])
for q in range(Q):
    l, r = map(int, input().split())
    output.append(ls[r]-ls[l-1])
print(*output, sep="\n")

Submission status: Accepted

Solution code:
import bisect, math
N = 10**5
Q = int(input())

lst1 = [2]
for L in range(3, N, 2):
  f = 0
  for d in range(3, math.floor(math.sqrt(L))+1, 2):
    if L % d == 0:
      f = 1
      break
  if f == 0:
    lst1.append(L)

lst1 = set(lst1) 
lst2 = [i for i in lst1 if (i+1)//2 in lst1]

lst2.sort()

for _ in range(Q):
  l, r = map(int, input().split())
  a = bisect.bisect_left(lst2, l)
  b = bisect.bisect_right(lst2, r)
  print(b-a)

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(10 ** 5 + 1)]
    A = tuple(accumulate(A))

    Q, *LR = map(int, open(0).read().split())
    ans = []
    for l, r in zip(*[iter(LR)] * 2):
        ans.append(A[r] - A[l - 1])

    print('\n'.join(map(str, ans)))
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(10 ** 5 + 1)]
    A = tuple(accumulate(A))

    Q, *LR = map(int, open(0).read().split())
    ans = []
    for l, r in zip(*[iter(LR)] * 2):
        ans.append(A[r] - A[l - 1])

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(10 ** 5 + 1)]
    A = tuple(accumulate(A))

    Q, *LR = map(int, open(0).read().split())
    ans = []
    for l, r in zip(LR[::2], LR[1::2]):
        ans.append(A[r] - A[l - 1])

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [n in primes and (n + 1) // 2 in primes for n in range(10 ** 5 + 1)]
    A = tuple(accumulate(A))

    Q, *LR = map(int, open(0).read().split())
    ans = []
    for l, r in zip(LR[::2], LR[1::2]):
        ans.append(A[r] - A[l - 1])

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [n % 2 and n in primes and (n + 1) // 2 in primes for n in range(10 ** 5 + 1)]
    A = tuple(accumulate(A))

    Q, *LR = map(int, open(0).read().split())
    ans = []
    for l, r in zip(LR[::2], LR[1::2]):
        ans.append(A[r] - A[l - 1])

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [n % 2 and n in primes and (n + 1) // 2 in primes for n in range(10 ** 5 + 1)]
    A = tuple(accumulate(A))

    Q, *LR = map(int, read().split())
    ans = []
    for l, r in zip(LR[::2], LR[1::2]):
        ans.append(A[r] - A[l - 1])

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [n % 2 and n in primes and (n + 1) // 2 in primes for n in range(10 ** 5 + 1)]
    A = tuple(accumulate(A))

    Q, *LR = map(int, read().split())
    ans = [0] * Q
    for i, (l, r) in enumerate(zip(LR[::2], LR[1::2])):
        ans[i] = A[r] - A[l - 1]

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import stdin, setrecursionlimit
from itertools import accumulate

setrecursionlimit(10 ** 9)
INF = 1 << 60


def input():
    return stdin.readline().strip()


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    N = 10 ** 5
    primes = prime_numbers(N)
    a = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(N + 1)]
    a = tuple(accumulate(a))

    ans = []
    Q, *LR = map(int, open(0).read().split())
    for l, r in zip(*[iter(LR)] * 2):
        ans.append(a[r] - a[l - 1])

    print('\n'.join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}


def main():
    primes = prime_numbers(10 ** 5)
    A = [n % 2 and n in primes and (n + 1) // 2 in primes for n in range(10 ** 5 + 1)]
    B = [0]
    B.extend(accumulate(A))

    Q, *LR = map(int, read().split())
    ans = [0] * Q
    for i, (l, r) in enumerate(zip(LR[::2], LR[1::2])):
        ans[i] = B[r + 1] - B[l]

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60


def prime_numbers(n):
    if n < 2:
        return []

    m = (n + 1) // 2
    p = [1] * m
    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):
        if p[i]:
            p[2 * i * (i + 1) :: 2 * i + 1] = [0] * (((m - 1) - 2 * i * (i + 1)) // (2 * i + 1) + 1)

    a = [2 * i + 1 for i in range(m) if p[i]]
    a[0] = 2
    return a


def main():
    primes = set(prime_numbers(10 ** 5))
    A = [n % 2 and n in primes and (n + 1) // 2 in primes for n in range(10 ** 5 + 1)]
    B = [0]
    B.extend(accumulate(A))

    Q, *LR = map(int, read().split())
    ans = [0] * Q
    for i, (l, r) in enumerate(zip(LR[::2], LR[1::2])):
        ans[i] = B[r + 1] - B[l]

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect

q = int(input())
plist = [2]
like2017 = []
n = 3
while n <= 10 ** 5:
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            break
    else:
        plist.append(n)
        if (n + 1) // 2 in plist:
            like2017.append(n)
    n += 2
for _ in range(q):
    l, r = map(int, input().split())
    print(bisect.bisect_right(like2017, r) - bisect.bisect_left(like2017, l))