Lucky Chains (Codeforces 1766D)
Tags: Math, number theory

Let's name a pair of positive integers $$$(x, y)$$$ lucky if the greatest common divisor of them is equal to $$$1$$$ ($$$\gcd(x, y) = 1$$$).Let's define a chain induced by $$$(x, y)$$$ as a sequence of pairs $$$(x, y)$$$, $$$(x + 1, y + 1)$$$, $$$(x + 2, y + 2)$$$, $$$\dots$$$, $$$(x + k, y + k)$$$ for some integer $$$k \ge 0$$$. The length of the chain is the number of pairs it consists of, or $$$(k + 1)$$$.Let's name such chain lucky if all pairs in the chain are lucky.You are given $$$n$$$ pairs $$$(x_i, y_i)$$$. Calculate for each pair the length of the longest lucky chain induced by this pair. Note that if $$$(x_i, y_i)$$$ is not lucky itself, the chain will have the length $$$0$$$. 

Input: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of pairs.Next $$$n$$$ lines contains $$$n$$$ pairs — one per line. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i < y_i \le 10^7$$$) — the corresponding pair.

Output: Print $$$n$$$ integers, where the $$$i$$$-th integer is the length of the longest lucky chain induced by $$$(x_i, y_i)$$$ or $$$-1$$$ if the chain can be infinitely long.

Note: In the first test case, $$$\gcd(5, 15) = 5 > 1$$$, so it's already not lucky, so the length of the lucky chain is $$$0$$$.In the second test case, $$$\gcd(13 + 1, 37 + 1) = \gcd(14, 38) = 2$$$. So, the lucky chain consists of the single pair $$$(13, 37)$$$. 

Sample Inputs:
4
5 15
13 37
8 9
10009 20000

Sample Outputs:
0
1
-1
79

Solution (Python):
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

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.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
    return int(input())

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

def gcd(a, b):
    while b:
        (a, b) = (b, a % b)
    return a
N = 10 ** 7
lp = [0] * (N + 1)
pr = []
for i in range(2, N + 1):
    if lp[i] == 0:
        lp[i] = i
        pr.append(i)
    for j in range(len(pr)):
        if i * pr[j] > N:
            break
        lp[i * pr[j]] = pr[j]
        if pr[j] == lp[i]:
            break

def prime_factors(n):
    ret = []
    while n > 1:
        p = lp[n]
        ret.append(p)
        while n % p == 0:
            n //= p
    return ret

def solve():
    (x, y) = rl()
    z = y - x
    if z == 1:
        print(-1)
    elif gcd(x, y) != 1:
        print(0)
    else:
        z = y - x
        ans = 10 ** 10
        for p in prime_factors(z):
            d = -x % p
            ans = min(ans, d)
        print(ans)
mode = 'T'
if mode == 'T':
    t = ri()
    for i in range(t):
        solve()
else:
    solve()

Solution (Python):
import os, sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop
from functools import lru_cache
from itertools import accumulate
import math
import sys
BUFSIZE = 8192

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.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ii = lambda : int(input())
mii = lambda : map(int, input().split())
fii = lambda : map(float, input().split())
lmii = lambda : list(map(int, input().split()))
i2c = lambda n: chr(ord('a') + n)
c2i = lambda c: ord(c) - ord('a')
mod = 998244353
N = 10 ** 7 + 2
D = [1] * N
for i in range(2, N):
    if D[i] > 1:
        continue
    else:
        for j in range(i, N, i):
            D[j] = i

def solve():
    (x, y) = mii()
    d = y - x
    if d == 1:
        print(-1)
        return
    P = set()
    while d != 1:
        P.add(D[d])
        d //= D[d]
    r = 10000000
    for p in P:
        u = x % p
        if u == 0:
            print(0)
            return
        u = p - u
        if u < r:
            r = u
    print(r)
for _ in range(ii()):
    solve()

Solution (Python):
import random
import bisect
import math
import itertools
import heapq
from functools import lru_cache
from collections import defaultdict, deque, Counter
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._file = 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.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
    return sys.stdin.readline().rstrip('\r\n')

def readint():
    return int(input())

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

class HashMap:

    def __init__(self, arg, strings=False):
        self.strings = strings
        self.magic = random.randrange(10 ** 8)
        if callable(arg):
            self.dict = defaultdict(arg)
        else:
            self.dict = defaultdict(int)
            for key in arg:
                self[key] += 1

    def __getitem__(self, key):
        return self.dict[key ^ self.magic]

    def __setitem__(self, key, val):
        self.dict[key ^ self.magic] = val

    def __contains__(self, key):
        return key ^ self.magic in self.dict

    def remove(self, key):
        del self.dict[key ^ self.magic]

    def items(self):
        for (key, val) in self.dict.items():
            yield (key ^ self.magic, val)

    def keys(self):
        for key in self.dict.keys():
            yield (key ^ self.magic)

    def values(self):
        return self.dict.values()

    def __iter__(self):
        for key in self.dict:
            yield (key ^ self.magic)

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

    def __str__(self):
        s = '{'
        for (key, val) in self.items():
            s += f'{key}:{val}, '
        s += '}'
        return s

class HashSet:

    def __init__(self):
        self.dict = HashMap(bool)

    def add(self, item):
        self.dict[item] = True

    def remove(self, item):
        self.dict.remove(item)

    def __contains__(self, key):
        return key in self.dict

    def __iter__(self, key):
        for key in self.dict:
            yield key

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

    def __str__(self):
        s = '{'
        for key in self:
            s += f'{key}, '
        s += '}'
        return s

class Sieve:

    def __init__(self, m):
        self.sieve = [-1] * (m + 1)
        self.prime = []
        for i in range(2, m + 1):
            if self.sieve[i] == -1:
                self.prime.append(i)
                self.sieve[i] = i
                j = 2 * i
                while j <= m:
                    self.sieve[j] = i
                    j += i

    def primes(self):
        return self.prime

    def factor(self, n):
        d = []
        while n != 1:
            p = self.sieve[n]
            e = 0
            while n % p == 0:
                e += 1
                n //= p
            d.append((p, e))
        return d

    def uniqueFactors(self, n):
        d = []
        while n != 1:
            p = self.sieve[n]
            while n % p == 0:
                n //= p
            d.append(p)
        return d

    def divisors(self, n):
        c = [1]
        while n != 1:
            p = self.sieve[n]
            cnt = 1
            n //= p
            while self.sieve[n] == p:
                cnt += 1
                n //= p
            s = c.copy()
            for i in s:
                for j in range(1, cnt + 1):
                    c.append(i * p ** j)
        return c
mod = 10 ** 9 + 7
sieve = Sieve(10 ** 7)
primes = sieve.primes()
t = readint()
for _ in range(t):
    (x, y) = readlist()
    if math.gcd(x, y) != 1:
        print(0)
        continue
    if x % 2 == 1 and y % 2 == 1:
        print(1)
        continue
    if x + 1 == y:
        print(-1)
        continue
    diff = y - x
    best = diff
    while diff != 1:
        f = sieve.sieve[diff]
        mod = x % f
        dist = f - mod
        best = min(best, dist)
        while diff % f == 0:
            diff //= f
    print(best)
    ''