LCM Sum (hard version)
We are sum for we are manySome NumberThis version of the problem differs from the previous one only in the constraint on $$$t$$$. You can make hacks only if both versions of the problem are solved.You are given two positive integers $$$l$$$ and $$$r$$$.Count the number of distinct triplets of integers $$$(i, j, k)$$$ such that $$$l \le i < j < k \le r$$$ and $$$\operatorname{lcm}(i,j,k) \ge i + j + k$$$.Here $$$\operatorname{lcm}(i, j, k)$$$ denotes the least common multiple (LCM) of integers $$$i$$$, $$$j$$$, and $$$k$$$.
In the first test case, there are $$$3$$$ suitable triplets:   $$$(1,2,3)$$$,  $$$(1,3,4)$$$,  $$$(2,3,4)$$$. In the second test case, there is $$$1$$$ suitable triplet:   $$$(3,4,5)$$$. 
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$\bf{1 \le t \le 10^5}$$$). Description of the test cases follows.The only line for each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 2 \cdot 10^5$$$, $$$l + 2 \le r$$$).
For each test case print one integer — the number of suitable triplets.
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        import math
        inf = math.inf

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')

class FenwickTree:

    def __init__(self, iter):
        self.bit = list(iter)
        self.n = len(self.bit)
        for i in range(self.n):
            if i | i + 1 < self.n:
                self.bit[i | i + 1] += self.bit[i]

    def sum(self, r):
        res = 0
        while r >= 0:
            res += self.bit[r]
            r = (r & r + 1) - 1
        return res

    def rsum(self, l, r):
        return self.sum(r) - self.sum(l - 1)

    def add(self, idx, delta):
        while idx < self.n:
            self.bit[idx] += delta
            idx = idx | idx + 1

def main():
    q = II()
    m = 2 * 10 ** 5
    ans = [0] * q
    queries = [[] for _ in range(m + 1)]
    for i in range(q):
        (l, r) = MII()
        ans[i] = (r - l + 1) * (r - l) * (r - l - 1) // 6
        queries[l].append(r * q + i)
    factor_counts = [0] * (m + 1)
    for i in range(1, m + 1):
        for j in range(i, m + 1, i):
            factor_counts[j] += 1
    tmp = [(x - 2) * (x - 1) // 2 for x in factor_counts]
    fen = FenwickTree(tmp)
    for l in range(1, m):
        for query in queries[l]:
            (r, i) = divmod(query, q)
            ans[i] -= fen.rsum(l, r) + max(r // 6 - (l - 1) // 3, 0) + max(r // 15 - (l - 1) // 6, 0)
        for j in range(l, m + 1, l):
            factor_counts[j] -= 1
            fen.add(j, 1 - factor_counts[j])
    print('\n'.join(map(str, ans)))
    return
t = 1
for _ in range(t):
    main()
from sys import stdin
input = lambda : stdin.readline()[:-1]

class segtree:

    def __init__(self, init, func, ide):
        self.n = len(init)
        self.func = func
        self.ide = ide
        self.size = 1 << (self.n - 1).bit_length()
        self.tree = [self.ide for i in range(2 * self.size)]
        for i in range(self.n):
            self.tree[self.size + i] = init[i]
        for i in range(self.size - 1, 0, -1):
            self.tree[i] = self.func(self.tree[2 * i], self.tree[2 * i | 1])

    def update(self, k, x):
        k += self.size
        self.tree[k] = x
        k >>= 1
        while k:
            self.tree[k] = self.func(self.tree[2 * k], self.tree[k * 2 | 1])
            k >>= 1

    def get(self, i):
        return self.tree[i + self.size]

    def query(self, l, r):
        l += self.size
        r += self.size
        l_res = self.ide
        r_res = self.ide
        while l < r:
            if l & 1:
                l_res = self.func(l_res, self.tree[l])
                l += 1
            if r & 1:
                r -= 1
                r_res = self.func(self.tree[r], r_res)
            l >>= 1
            r >>= 1
        return self.func(l_res, r_res)

    def debug(self, s=10):
        print([self.get(i) for i in range(min(self.n, s))])
m = 2 * 10 ** 5 + 10
query = [[] for i in range(m)]
q = int(input())
for i in range(q):
    (l, r) = map(int, input().split())
    query[l].append((r, i))
tmp = [0] * m
for i in range(1, m):
    for j in range(i, m, i):
        tmp[j] += 1
seg = segtree([(i - 1) * (i - 2) // 2 for i in tmp], lambda x, y: x + y, 0)
ans = [0] * q
for L in range(1, m):
    for (R, i) in query[L]:
        d = R - L + 1
        res = d * (d - 1) * (d - 2) // 6 - seg.query(L, R + 1)
        res -= max(R // 6 - (L - 1) // 3, 0)
        res -= max(R // 15 - (L - 1) // 6, 0)
        ans[i] = res
    for j in range(L, m, L):
        tmp[j] -= 1
        seg.update(j, (tmp[j] - 1) * (tmp[j] - 2) // 2)
for i in ans:
    print(i)
""""""
import io, os, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
output = sys.stdout.write

def debug(*args):
    if os.environ.get('debug') in [None, '0']:
        return
    from inspect import currentframe, getframeinfo
    from re import search
    frame = currentframe().f_back
    s = getframeinfo(frame).code_context[0]
    r = search('\\((.*)\\)', s).group(1)
    vnames = r.split(', ')
    var_and_vals = [f'{var}={val}' for (var, val) in zip(vnames, args)]
    prefix = f'{currentframe().f_back.f_lineno:02d}: '
    print(f"{prefix}{', '.join(var_and_vals)}")
from types import GeneratorType

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        to = f(*args, **kwargs)
        while True:
            if type(to) is GeneratorType:
                stack.append(to)
                to = next(to)
            else:
                stack.pop()
                if not stack:
                    break
                to = stack[-1].send(to)
        return to
    return wrappedfunc

class IntKeyDict(dict):
    from random import randrange
    rand = randrange(1 << 62)

    def __setitem__(self, k, v):
        super().__setitem__(k ^ self.rand, v)

    def __getitem__(self, k):
        return super().__getitem__(k ^ self.rand)

    def __contains__(self, k):
        return super().__contains__(k ^ self.rand)

    def __repr__(self):
        return str({k: v for (k, v) in self.items()})

    def get(self, k, default=None):
        return super().get(k ^ self.rand, default)

    def keys(self):
        return [k ^ self.rand for k in super().keys()]

    def items(self):
        return [(k ^ self.rand, v) for (k, v) in super().items()]
INF = float('inf')

def get_lpf(N):
    lpf = [1] * (N + 1)
    primes = []
    for i in range(2, N + 1):
        if lpf[i] == 1:
            lpf[i] = i
            primes.append(i)
        for p in primes:
            if p * i > N or lpf[i] < p:
                break
            lpf[p * i] = p
    return lpf
MAX = 2 * 10 ** 5
LPF = get_lpf(MAX)

def get_divisors(x):
    cur = [1]
    while x > 1:
        (p, cnt) = (LPF[x], 0)
        while x % p == 0:
            cnt += 1
            x //= p
        nxt = []
        for d in cur:
            for i in range(1, cnt + 1):
                nxt.append(d * p ** i)
        cur.extend(nxt)
    return cur

class FenwickTree:
    """"""

    def __init__(self, data):
        """"""
        self.val = data[:]
        for i in range(len(self.val)):
            j = i | i + 1
            if j < len(self.val):
                self.val[j] += self.val[i]

    def __len__(self):
        return len(self.val)

    def query(self, i):
        """"""
        s = 0
        end = i + 1
        while end:
            s += self.val[end - 1]
            end &= end - 1
        return s

    def query_range(self, l, r):
        """"""
        return self.query(r) - self.query(l - 1)

    def add(self, i, x):
        """"""
        while i < len(self.val):
            self.val[i] += x
            i |= i + 1

def solve(segs, Q):
    res = [0] * Q
    fw = FenwickTree([0] * (MAX + 1))
    idx = sorted(list(range(Q)), key=lambda i: (segs[i][1], segs[i][0]))
    last = 1
    for i in idx:
        (l, r) = segs[i]
        for c in range(last, r + 1):
            divs = sorted(get_divisors(c))[:-1]
            for (j, a) in enumerate(divs):
                fw.add(a, len(divs) - 1 - j)
            if c % 6 == 0:
                fw.add(c // 2, 1)
            if c % 15 == 0:
                fw.add(2 * c // 5, 1)
        res[i] = (r - l + 1) * (r - l) * (r - l - 1) // 6 - fw.query_range(l, r)
        last = r + 1
    return res

def main():
    Q = int(input())
    segs = [list(map(int, input().split())) for _ in range(Q)]
    out = solve(segs, Q)
    print(*out, sep='\n')
if __name__ == '__main__':
    main()