# IIS-L-27128 (MO 509825): for n>2, are there digits 1<=a,b<n, (a,b)!=(1,1), with a*n+b and b*n+a both prime?
# Robert Israel's claim: for 3<=n<=10^6, a=1 and some 1<b<n work. Check it to N; report the largest least-b/n.
# Deterministic Miller-Rabin (bases 2..17, valid below 3.4e14) with 21-bit split mulmod (moduli < 2^42).
import sys, numba as nb, numpy as np
N = int(float(sys.argv[1])) if len(sys.argv) > 1 else 10**6
assert N * N < 2**42
@nb.njit(cache=True)
def mulmod(a, b, m):
    hi = b >> 21; lo = b & ((1 << 21) - 1)
    return ((((a * hi) % m) << 21) % m + a * lo) % m
@nb.njit(cache=True)
def powmod(a, e, m):
    r = 1; a %= m
    while e:
        if e & 1: r = mulmod(r, a, m)
        a = mulmod(a, a, m); e >>= 1
    return r
@nb.njit(cache=True)
def isprime(n):
    if n < 2: return False
    for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
        if n % p == 0: return n == p
    d = n - 1; s = 0
    while d % 2 == 0: d //= 2; s += 1
    for a in (2, 3, 5, 7, 11, 13, 17):
        x = powmod(a, d, n)
        if x == 1 or x == n - 1: continue
        ok = False
        for _ in range(s - 1):
            x = mulmod(x, x, n)
            if x == n - 1: ok = True; break
        if not ok: return False
    return True
@nb.njit(cache=True)
def run(N):
    nfail = 0; firstfail = -1; worst = 0.0; worstn = 0
    for n in range(3, N + 1):
        found = False
        for b in range(2, n):
            if isprime(n + b) and isprime(b * n + 1):
                if n >= 1000 and b / n > worst: worst = b / n; worstn = n
                found = True; break
        if not found:
            nfail += 1
            if firstfail < 0: firstfail = n
    return nfail, firstfail, worst, worstn
# self-check of isprime against a sieve
S = np.ones(200000, np.bool_); S[:2] = False
for i in range(2, 448):
    if S[i]: S[i*i::i] = False
assert all(isprime(i) == S[i] for i in range(200000))
assert isprime(999999999989) and not isprime(999999999987) and isprime(2**41 - 21) is not None
print("N =", N, "(nfail, first fail, max least-b/n for n>=1000, at n) =", run(N))
