A set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number. Of the four prime numbers that make up a quadruplet prime, the largest number is called the size of the quadruplet prime. For example, the smallest prime quadruplet is a set of (5, 7, 11, 13), which is 13 in size. The next largest prime quadruplet is the set of (11, 13, 17, 19), which is 19 in size.
Create a program that takes the integer n (13 ≤ n ≤ 10,000,000) as
input and outputs the maximum size of the quadruplet prime numbers whose size is n or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. One integer n is given on one row for each dataset.
The number of datasets does not exceed 2000.
Output
Outputs the maximum prime quadruplet size on one line for each input dataset.
Example
Input
13
14
15
16
17
18
19
20
10000
0
Output
13
13
13
13
13
13
19
19
9439
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve problem: Given n (13 ≤ n ≤ 10,000,000), find the maximum size (largest prime) of a prime quadruplet of the form (a, a+2, a+6, a+8) where all four numbers are prime, and the largest (a+8) ≤ n. Output that size. If no such quadruplet exists with size ≤ n, maybe output something? But constraints ensure n≥13, smallest is 13, so there will be at least for n≥13? Actually for n=13, we have quadruplet (5,7,11,13) with size 13; for n=14,15,16,17,18, size 13 is ≤n, so output 13. For n=19, the next quadruplet has size 19, so max is 19. So it's always at least 13. But might be that for some n between 13 and 19, only the first one works. So we need to compute up to n max=10,000,000. Number of datasets ≤2000.
We need to precompute all prime quadruplets up to 10,000,008 maybe? Since size is a+8, and n max 10,000,000, we need primes up to 10,000,008 (since a+8 ≤ n). Actually we can generate primes up to 10,000,008 (10 million + 8). That's doable with sieve of Eratosthenes. Memory: boolean array of 10,000,009 bits or bytes. 10 million bytes = 10 MB, acceptable. Could use bitset to reduce memory, but 10 MB is fine. However number of datasets up to 2000, we need fast query: for each n, find the largest a+8 ≤ n such that (a, a+2, a+6, a+8) are all prime. Could precompute an array answer[] of size max_n+1 where answer[i] = max size ≤ i. Compute all quadruplets, then fill answer array: for each quadruplet with size s, update max up to index s. But size s ≤ 10,000,000, so we can create array ans[0..max_n] initially 0, then for each quadruplet set ans[s] = s, then do prefix max: for i from 1 to max_n: ans[i] = max(ans[i], ans[i-1]). Or we can simply store all sizes in a sorted list, then for each query binary search for largest size ≤ n. That's easier: collect sizes of all prime quadruplets (a+8) up to max_n, sort them. Then for each n, binary search (upper_bound) the largest ≤ n.
Given max_n=10,000,000, the number of prime quadruplets within that range? Let's estimate. Prime quadruplets are of the form (p, p+2, p+6, p+8). They are also known as prime quadruplets, and there's known density: they are very rare. For 10 million, the number might be around maybe a few hundred? Let's estimate: According to known data, prime quadruplets up to 10^8 are about 8998 (I recall something like that). Actually, known: number of prime quadruplets up to 10^8 is 899? Let's check: Known prime quadruplets: The smallest pattern: except (5,7,11,13) the rest start with p = 11 mod 30? Actually p > 5 must be of the form 30k+11 or 30k+? Let's deduce: For p > 5, all primes >5 are ≡ 1,7,11,13,17,19,23,29 mod 30. For quadruplet (p, p+2, p+6, p+8), we need p mod 30? Consider mod 5 and mod 3: p, p+2, p+6, p+8. mod 5: p can't be 0 mod5; p+2 can't be 0; p+6 can't be 0; p+8 can't be 0. So p mod 5 cannot be 0,3,4,2? Let's compute: if p ≡ 0 mod5 -> p is divisible by 5, only prime if p=5. p ≡1 -> p+2≡3 mod5, p+6≡7≡2 mod5, p+8≡9≡4 mod5, all not divisible by 5. p≡2 -> p+2≡4, p+6≡8≡3, p+8≡10≡0 -> divisible by 5 unless a+8=5? but a+8>5 usually. So p≡2 mod5 invalid for a>5. p≡3 -> p+2≡0 mod5 invalid. p≡4 -> p+2≡1, p+6≡10≡0 invalid. So only p≡0 (p=5) or p≡1 mod5 for p>5. So p mod5 = 1.
Now mod 3: p, p+2, p+6, p+8. p mod3 cannot be 0 (except p=3). p mod3=1: then p+2≡0 mod3 -> invalid unless p+2=3? but that would be p=1 not prime. p mod3=2: then p+2≡1, p+6≡8≡2, p+8≡10≡1 -> none 0 mod3? p mod3=2: p+6 ≡ 8 mod3 = 2? Actually 2+6=8 mod3=2, okay. So p mod3 must be 2. Combined mod5=1 and mod3=2 => mod15? Solve p ≡ 1 mod5, p ≡ 2 mod3. Using CRT: mod15: numbers 0..14: which satisfy 1 mod5: 1,6,11. Among these, which ≡2 mod3? 1 mod3=1;6 mod3=0;11 mod3=2. So p ≡11 mod15. But also consider mod2: p odd obviously. So p ≡ 11 mod 30? Let's check mod30: numbers ≡11 mod30: 11,41,71,... Also numbers ≡? p=5 is special. For p>5, p ≡ 11 mod 30? Let's test known quadruplets: 11, 101, 191, 821, etc. Indeed p = 30k+11 seems to generate quadruplets sometimes. But also p = 30k+? Wait, let's test p=5? Not mod30? Actually p=5 works but it's not of that pattern? 5,7,11,13: 5 mod30=5. But for p>5, it's known that prime quadruplets are of form 30k+11, 30k+13? Actually check: (11,13,17,19): p=11 mod30=11. Next quadruplet: (101,103,107,109): p=101 mod30= 101 mod30 = 11? 303=90, remainder 11. Next: (191,193,197,199): 191 mod30= 11? 306=180 remainder 11. So indeed p ≡ 11 mod30. But is there possibility p ≡ something else? Let's check mod7 etc not necessary. But it's known that prime quadruplets (except 5,7,11,13) are of the form (30n+11, 30n+13, 30n+17, 30n+19). Actually that's exactly the pattern: p=30n+11, then p+2=30n+13, p+6=30n+17, p+8=30n+19. So they are twin primes pairs separated by 6 (so-called "quadruple primes"). So indeed for p>5, p ≡ 11 mod 30. So we can sieve only numbers that are 11 mod 30? But careful: The quadruplet's largest is p+8 = 30n+19. So the size s = 30n+19. So we can generate candidate n such that all four numbers are prime.
Thus the number of quadruplets up to 10 million is roughly? x/(log^4 x) times constant? Actually conjectured number of prime quadruplets up to N is about constant * N/(log^4 N) where constant? But for N=10^7, log(10^7) ~ 16.1, so log^4 ~ (16.1)^4 ≈ 16.1^2=259, squared=~67k, so N/log^4 N ≈ 10^7 / 67000 ≈ 149. So expect around 150? But let's check known counts: I recall prime quadruplets up to 10^7 maybe around 200? Let's quick search memory: Up to 10^8, there are 899 prime quadruplets? Actually I recall that prime quadruplets up to 10^9 are about 4768? I'm not sure. Let's compute roughly: Known result: Number of prime quadruplets (p,p+2,p+6,p+8) with p ≤ 10^7: I can approximate using known data: According to OEIS A007530 (values of p for prime quadruplets): The first few: 5,11,101,191,821,1481,1871,2081,3251,... The count up to 10^7? I can quickly simulate mentally? Not needed. But we can precompute all primes up to 10,000,008 with sieve, then check quadruplets straightforwardly. 10 million is fine.
Time: Sieve up to 10,000,008 using O(N log log N) ~ about maybe 0.1 sec in C++? In Python, with careful optimization might be borderline but possibly okay if using bytearray and efficient loops. But we need to handle up to 2000 queries, but after precomputation, queries are trivial. The challenge is Python runtime: Sieve up to 10 million in Python is doable with typical optimizations (e.g., using bytearray, marking only odd numbers). 10 million booleans in a bytearray is 10 MB. Loops marking multiples of primes up to sqrt(10M) ≈ 3162. That's not many. However marking all odd composites from 3 to 10M might be done with standard sieve. This should be fast (maybe <0.5 sec). Then scanning for quadruplets: iterate a from 5? Actually we need to include the special case a=5 gives (5,7,11,13). That pattern: a=5 gives a+2=7, a+6=11, a+8=13. All primes. So that's a quadruplet. For a>5, pattern is a ≡ 11 mod 30. But we can simply test all odd a up to n-8 (but n max 10M) and check if a, a+2, a+6, a+8 are all prime using the sieve. That would be O(n) scanning 10M times, which is fine (~10M checks). Each check would involve 4 array lookups, which is okay. But we can also restrict to candidates a where a%30==11 or a=5. That reduces scanning to about N/30 ≈ 333k candidates, which is even faster. So we can implement that.
After we get list sizes = [13, 19, ...] sorted. Then for each input n (until 0), binary search: find the largest element ≤ n. Since list is sorted, we can use bisect_right.
Edge cases: n may be 13? Then output 13. n=14 -> 13. For n<13? Input says n ≥ 13, but final line is 0. So fine.
But note: The problem statement: "The integer n (13 ≤ n ≤ 10,000,000)". So n starts at 13. So we can assume.
Now implement.
Approach steps:
Set MAX_N = 10000000 (10 million). Since sizes go up to MAX_N, we need primes up to MAX_N+8 = 10000008 (since a+8 could be MAX_N). Actually if n=10,000,000, a+8 can be exactly 10,000,000. So need prime check for numbers up to 10,000,008? Because a+8 ≤ 10,000,000, but a itself ≤ 10,000,000-8=9,999,992, a+6= a+6 ≤ 9,999,998, a+2 ≤ 9,999,994, a ≤ 9,999,992. So max prime needed is a+8 = 10,000,000. However if we consider a candidate a ≡ 11 mod 30, we might generate a up to 10,000,000-8 = 9,999,992, but we need to check a+8 = 10,000,000 for primality. So we need primality up to 10,000,000. So we can set limit = 10,000,000. However a=5 case: a+8=13 < limit. So we can sieve up to MAX_N = 10,000,000. But careful: For checking a+8 ≤ n, n can be up to 10,000,000. So we need prime check up to 10,000,000. That's fine.
But while scanning candidates a, we need to check a+8 ≤ MAX_N? Actually we only need quadruplets with size ≤ MAX_N. Since we are building list of sizes ≤ MAX_N, we can limit a to MAX_N-8. So we will only consider a such that a+8 ≤ MAX_N. So we need prime check for numbers up to MAX_N (since a+8 ≤ MAX_N). So we can sieve up to MAX_N.
So define LIMIT = 10000000.
Sieve of Eratosthenes to get boolean array is_prime[0..LIMIT] (or maybe only odd indices). For simplicity, use bytearray of size LIMIT+1. Mark all numbers as prime initially (except 0,1). Then for i from 2 to sqrt(LIMIT): if is_prime[i], then mark multiples starting from i*i as not prime.
We can optimize by only considering odd numbers to save memory/time. But with LIMIT=10M, bytearray of 10M+1 = ~10MB, okay. Sieve can be done like:
def sieve(limit):
is_prime = bytearray(b'\x01') * (limit+1)
is_prime[0:2] = b'\x00\x00'
for i in range(2, int(limit**0.5)+1):
if is_prime[i]:
step = i
start = i*i
is_prime[start:limit+1:step] = b'\x00' * ((limit - start)//step + 1)
return is_prime
But this uses slicing assignment which is fast but careful: need to compute length correctly. Alternatively, we can use standard for loops with step. In Python, slicing assignment with bytes multiplication is efficient. However creating a large bytes object for each prime might be heavy? Actually the slice assignment with b'\x00' * length is okay if length is moderate. But for large ranges like i=2, length about 5M, that's big but okay. However total operations might be many but still acceptable.
Better optimization: only consider odd numbers. We can store only odd numbers index, halving memory. But maybe not necessary.
But we need to test numbers up to 10M, and prime checking for even numbers >2 is trivial false. So we can just have full array. I think it's fine.
After sieve, we need to collect quadruplet sizes.
Initialize list sizes = [].
First, handle a=5: check if 5,7,11,13 are prime. Since 5,7,11,13 are primes, always true. But need to ensure we include only if size (13) ≤ LIMIT. Since LIMIT=10M, include.
Add 13 to sizes.
Now for a from 11 to LIMIT-8, step 30 (since a%30==11). Actually a starts at 11 because 11 is first candidate after 5. But note: 11 gives quadruplet (11,13,17,19) all primes, so works.
So for a in range(11, LIMIT-7, 30): (LIMIT-8 inclusive). Check if is_prime[a] and is_prime[a+2] and is_prime[a+6] and is_prime[a+8]. If yes, append a+8 to sizes.
But careful: For a=11, a+8=19; all primes. Good.
But what about a=5? Already handled.
After collecting sizes, sort. Actually they are increasing automatically because we iterate a increasing, so sizes list will be increasing. So we can skip sorting.
Then process input lines: read integers until 0. For each n, binary search to find largest size ≤ n.
We can use bisect from bisect module:
import bisect
idx = bisect.bisect_right(sizes, n) - 1
if idx >= 0: print(sizes[idx])
else: print(0) but never happen because smallest size=13 and n>=13.
But note: Could there be cases where there is no quadruplet with size ≤ n? For n=13, smallest is 13, so idx>=0. So fine.
Now we need to consider potential issues: The input may include multiple datasets up to 2000, but reading and processing is trivial.
Edge Cases: n may be 13? Already.
But need to ensure that we consider the maximum size ≤ n. That's what binary search does.
Now test with given example:
Input:
13
14
15
16
17
18
19
20
10000
0
Our code: sizes: [13,19, ...] Next after 19? Let's compute next quadruplet: (101,103,107,109) size 109. So list includes 13,19,109,... So for n=20, binary search largest ≤20: 19. For n=19: 19. For n=18: 13. For 10000: which quadruplet sizes ≤10000? Let's compute manually: The quadruplets up to 10000: sizes: 13,19,109, 199? Actually (191,193,197,199) size 199. (821,823,827,829) size 829. (1481...) size 1489? Actually (1481,1483,1487,1489) size 1489. (1871...) size 1879. (2081...) size 2089. (3251...) size 3259. (3461) size 3469? Wait need to verify: Actually pattern: p=11 -> size=19; p=101 -> size=109; p=191 -> size=199; p=821 -> size=829; p=1481 -> size=1489; p=1871 -> size=1879; p=2081 -> size=2089; p=3251 -> size=3259; p=3461 -> size=3469; p=5651 -> size=5659; p=9431? Actually p=9431? 9431 mod30? 30314=9420, remainder 11, so p=9431? But 9431 is not prime? Let's check known list: Prime quadruplets: 5, 11, 101, 191, 821, 1481, 1871, 2081, 3251, 3461, 5651, 9431? Actually 9431? 9431 = 9431/?? 9431/17=554.76? Not sure. Actually known list: I recall: after 5651 comes 9431? Maybe 9431? But size would be 9439 (since p+8). Given example output for n=10000 is 9439, so indeed the largest quadruplet ≤ 10000 has size 9439. So p = 9431? 9431+8=9439. Check: 9431 is prime? I think 9431 is prime? 9431 = 9431/13 = 725.46? 13725 = 9425, remainder 6; /17 = 17555=9435, no; /19=19496=9424, remainder 7; /31=31*304=9424 remainder 7; /7=1347.285. Might be prime. So yes. So our algorithm should find that.
Thus correct.
Now implementation details:
We must ensure sieve up to 10,000,000 is efficient in Python. Let's test approximate runtime: 10 million bytearray, marking multiples from 2 to sqrt(10M) ~ 3162. For each prime, we mark multiples. However for small primes like 2, we mark half of the array, which is 5 million operations via slice assignment, which is fast because it's in C. For 3, mark about 3.33 million. For 5, 2 million. Sum of (N/p) for p up to 3162. Approx N * sum_{p ≤ sqrt(N)} 1/p, but early primes dominate. The total number of markings via slice assignment might be okay. But careful: the slice assignment with b'\x00' * length creates a bytes object of length proportional to number of elements to assign. For large ranges (like 5 million), this creates a huge bytes string of 5 million bytes, which is 5 MB, but that's temporary and then assigned to slice; this may be memory heavy but okay. However we can also use loop with step, but slice assignment is generally fastest.
Alternative: use built-in array of booleans from Python's list of bool? That would be much bigger memory (10M * 28 bytes? Too large). So bytearray is good.
Potential memory: 10 million bytes = ~9.5 MB, plus overhead, fine.
But note: we need to include number 0 and 1 as not prime. So initialize:
Now for i in range(2, int(LIMIT**0.5) + 1):
if is_prime[i]:
is_prime[ii : LIMIT+1 : i] = b'\x00' * ((LIMIT - ii)//i + 1)
But careful: The slicing syntax is bytearray[start:stop:step] = b'\x00'length. However when we assign to a slice with a step, the length of the assigned bytes must match the number of elements in the slice. The expression ((LIMIT - ii)//i + 1) gives exactly the count. This works.
But there is a nuance: For large i, ii may overflow? Not for i ≤ 3162, ii ≤ ~10M, fine.
This will work.
But there is also a potential for the slice assignment to be inefficient if the step is not 1? Actually when we use step i, the slice is a generalized slice, but assignment with a bytes of appropriate length works. However I'm not 100% sure about performance: Typically using is_prime[ii::i] = b'\x00'... is okay.
Alternatively, we could optimize by only marking odd numbers and handle 2 separately. But simpler is fine.
After sieve, we can quickly test: is_prime[2] = 1; etc.
Now scanning candidates:
sizes = []
if LIMIT >= 13:
sizes.append(13) # always?
But need to ensure we don't add 13 if a=5 quadruplet is not valid? It's valid, but if LIMIT <13? But LIMIT >=13 because n >=13, but we need to generate sizes for all possible n up to 10M, so include.
Now for a in range(11, LIMIT-7, 30):
if is_prime[a] and is_prime[a+2] and is_prime[a+6] and is_prime[a+8]:
sizes.append(a+8)
But careful: The candidate a must be such that a+8 ≤ LIMIT. Since we loop up to LIMIT-8 inclusive? range(11, LIMIT-7, 30) because stop is exclusive. To include a such that a ≤ LIMIT-8, we set stop = LIMIT-7 (since exclusive) or LIMIT-8+1 = LIMIT-7. So range(11, LIMIT-7, 30) will include a values up to the largest ≤ LIMIT-8.
But need to consider also a=5? Already handled. Also is there any other quadruplet pattern? For p=5, it's the only one not following 30k+11. So fine.
Now, there might be also quadruplet with a=7? Let's check: (7,9,13,15) not primes. So no.
Thus done.
Now test: For n=13, sizes list includes 13. binary search: idx = bisect_right([13,19,...],13)-1 = 1-1=0 -> 13.
Now complexity: scanning all a up to 10M step 30 ~ 333,334 iterations, each doing 4 array lookups and maybe short-circuit. That's fine.
But we must ensure that the prime array includes indices up to LIMIT (10,000,000). So we must not access out-of-range when a+8 = LIMIT, that's within. When a = LIMIT-8, a+8 = LIMIT, index exists.
Edge Cases: If LIMIT is less than 13? But we won't.
Now potential pitfalls:
The input may contain multiple datasets and the last line 0. So we need to read all lines, parse ints, stop when 0.
There might be blank lines? Not likely.
Output each answer on its own line.
Now can we reduce memory further? 10M bytes is okay.
But I recall that Python's slice assignment with step may be slower for large step? Actually I think it's okay. Another approach: use a bitarray library, but not allowed in standard environment? The problem is from an online judge (maybe AIZU or something), which typically uses pure Python, so we must rely on built-in modules only (like bisect, sys). So we can't use numpy or bitarray.
Thus the plan is solid.
We need to be careful about time: Sieve of Eratosthenes up to 10M in pure Python can be done within time if optimized. I've implemented similar before: using bytearray and marking from i*i with step i using slice assignment is reasonably fast, maybe around 0.5-1 second. The scanning of candidates and binary search is trivial. For 2000 queries, binary search is O(log K) each.
But we need to consider that the problem might have time limit strict, maybe 1-2 seconds. However Python may be borderline but often accepted with optimized code.
We can also precompute answer array of length LIMIT+1: for each quadruplet size s, set ans[s] = s, then do running max, and then answer queries in O(1). But that would require an array of size 10M+1 of integers (maybe 4 bytes each) -> 40 MB, might be okay but large. However we can store only the sizes list and binary search. That's simpler and memory efficient.
Alternatively, we can precompute all quadruplet sizes and then for each n, perform a while loop scanning from end of list? But binary search is fine.
Now we need to implement reading efficiently: use sys.stdin.read() to get all ints.
Implementation steps:
import sys, bisect
def main():
data = sys.stdin.read().strip().split()
if not data:
return
nums = list(map(int, data))
# The last is 0? but there may be multiple zeros? The input ends with 0. So we should process until 0.
queries = []
for x in nums:
if x == 0:
break
queries.append(x)
# Determine max_n among queries to possibly limit sieve size? But problem says n up to 10M. We could sieve up to max(queries) to save time if max_n is lower. But since max can be 10M, we can just sieve up to 10M. However if queries have max_n smaller, we can limit sieve to that max_n to be faster. But we also need to consider that quadruplet sizes <= max_n. So we could compute up to max(queries). But if there are many queries, it's fine to compute up to 10M anyway. But we might optimize by using dynamic limit: if max_n < some threshold, we can sieve only to that. But we must be careful: if the largest query is less than 10M, we might need only up to that value. But to be safe, we can compute up to 10M always. However if we have many datasets, but the largest n is smaller, we could reduce. But it's not needed.
code
But careful: The sieve marking with slice assignment: is_prime[start:limit+1:step] = b'\x00' * count. That works because the slice will have exactly count elements. However, when step is large, the slice assignment with a step may be less efficient but still okay. There is a known issue: For bytearray, slice assignment with step uses the same algorithm as loop? But it's in C, so it's fine.
But we must ensure count is integer and not huge. For i=2, start=4, count = (limit-4)//2+1 ≈ limit/2, e.g., for limit=10M, count=5M. b'\x00'*5M creates a 5MB bytes object. That's okay. But the total sum of counts across all primes is about N * log log N? Actually total assignments roughly N * (1/2 + 1/3 + 1/5 + ... ) but the slice assignment creates a temporary bytes for each prime, which could lead to high memory allocation and time. However the overhead may still be acceptable for 10M. I've seen such sieve code pass for 10^7 in Python. But we can optimize by using memoryview? Not necessary.
Alternatively, we can implement standard sieve using only odd numbers to halve memory and marking loops with for j in range(i*i, limit+1, i). But that's Python loop, slower. However for i up to sqrt(limit), marking multiples with Python loop might be slower due to Python overhead. But we can mix: Use slice assignment for small i? Actually slice assignment is fast.
Better: Use the typical "Sieve of Eratosthenes using bytearray" pattern:
def sieve(n):
is_prime = bytearray(b'\x01') * (n+1)
is_prime[:2] = b'\x00\x00'
for i in range(2, int(n**0.5)+1):
if is_prime[i]:
is_prime[ii:n+1:i] = b'\x00' * ((n - ii)//i + 1)
return is_prime
This is common and works for n up to 10^7 or even 10^8 (though 10^8 might be memory heavy). I think it's fine.
One more nuance: The slicing assignment for bytearray with step might not accept a bytes object of different length if the slice length is not exactly the same? Actually, Python requires that the length of the assigned sequence matches the number of elements in the slice when using extended slicing (step != 1). So we must compute count correctly. The expression ((n - ii)//i + 1) is indeed the number of elements from ii to n inclusive step i. That's correct.
Now note: For large i, ii may exceed n, then count would be negative? But loop condition ensures i <= sqrt(n), so ii <= n, so start <= n.
Thus ok.
Now we must ensure that we don't run into memory error when creating b'\x00'*count for large count. For i=2 and n=10M, count ≈5,000,000, which creates a bytes object of 5 MB. Then for i=3, count≈3,333,333, another ~3.3 MB, etc. The total sum of these temporary bytes may be large, but they are created sequentially and freed after assignment, so peak memory might be about the largest bytes object (5 MB) plus the bytearray (10 MB) ~15 MB. That's acceptable.
But we also have is_prime 10 MB, plus some overhead, total maybe 20 MB. Acceptable.
Now, potential performance: The slice assignment for each prime may involve iterating over the slice and setting bytes. This is done in C and should be fast. I've run similar code before, sieve up to 10^7 within <0.5 seconds.
But the judge environment might be slower; still likely fine.
Alternatively, we can further optimize by ignoring even numbers. We could allocate is_prime only for odd numbers: size (limit+1)//2. Then adjust indices. But then we need to check primality for even numbers quickly (only 2 is prime). That reduces memory to ~5 MB and speeds up marking because we only mark odd multiples. But the complexity of mapping indices might complicate the candidate checks. But we can do it.
Given simplicity, I'll go with full bytearray.
Now, note: The prime check for numbers like 2,3,5 etc. Our sieve includes them. For candidate a=5, we check is_prime[5],7,11,13. Works.
Now check candidate a=11: is_prime[11] true? It will be marked prime if not marked as composite. Since 11 is prime.
Edge: Is 1 considered prime? No, we set is_prime[1]=0.
Now we must ensure that we have primes up to limit inclusive. So for limit=10M, works.
Now about reading input: Might have trailing spaces. We'll use sys.stdin.read().
Now, potential bug: The list sizes may not contain values if limit < 13? But queries have n≥13, so limit ≥13. So sizes will at least have 13 if 13 ≤ limit. But we check: if limit >=13, we add 13 after verifying primality. Since 5,7,11,13 are prime, it's fine.
But what if limit is 13? Then we add 13. Then for a loop: range(11, limit-7, 30). limit-7 = 6? Actually limit=13, limit-7=6, start=11 >6, so loop empty. So sizes = [13]. Good.
Now binary search: for n=13, idx = bisect_right([13],13)-1 = 1-1=0 ->13. For n=12? But n is at least 13 per problem statement, but if there is n=12? Not allowed. So fine.
Now handle queries: need to output for each input in order.
Now, test with example.
Let's simulate quickly:
limit = max of [13,14,15,16,17,18,19,20,10000] = 10000.
Sieve up to 10000.
Then sizes: add 13. Then loop a from 11 to 10000-8=9992? Actually limit-7 = 9993? Since limit=10000, limit-7=9993, so range(11,9993,30) includes a=11,41,71,... up to a=?? Let's compute a max <= 9992: 30332 + 11 = 9971? 30332=9960, +11=9971. 9971+8=9979 <=10000. Next 30*333+11=10001 > limit-8. So includes. Then check quadruplets. Among them, sizes will include 13,19,109,199,829,1489,1879,2089,3259,3469,5659,9439,... Up to 10000, the last size is 9439. So sizes list: [13,19,109,199,829,1489,1879,2089,3259,3469,5659,9439]. Then for each query, binary search gives expected outputs: For 13-18 ->13; for 19,20 ->19; for 10000 ->9439. Good.
Now we need to ensure we include all quadruplets. But note: The quadruplet with p=5 is only one not following 30k+11. So we included manually. Also, are there any other exceptions? There is known quadruplet (p,p+2,p+6,p+8) only forms when p=5 or p ≡ 11 mod 30. So our scanning covers all p>5. So good.
Potential pitfall: In some definitions, prime quadruplets exclude the (5,7,11,13) because it's considered as the only one containing 5? But the problem says "a set of four prime numbers arranged like (a, a + 2, a + 6, a + 8) is called a quadruplet prime number." So (5,7,11,13) qualifies. So we include.
Now, I'll write the code accordingly.
But we should test performance: for limit = 10,000,000, the sieve and scanning should be fast.
One more optimization: Since we are only interested in primes for checking quadruplets, and quadruplets are only for numbers ≡ 11,13,17,19 mod 30? Actually we only need to test primality for numbers of the form 30k+11, 30k+13, 30k+17, 30k+19? But we are scanning candidates a ≡ 11 mod 30, and then checking a, a+2 (≡13 mod30), a+6 (≡17 mod30), a+8 (≡19 mod30). So all numbers we need to check are exactly those residues mod30. So we could restrict the sieve to numbers that are not divisible by 2,3,5? But we still need primality for all numbers for the sieve marking. However we can reduce the memory by storing only numbers coprime to 30? That might be overkill.
Simpler is fine.
Now, about the prime array: We'll use bytearray. When we assign is_prime[i*i:limit+1:i] = b'\x00' * count, this may produce a MemoryError if count is huge and we try to allocate a bytes of size count. For i=2 and limit=10,000,000, count ~5,000,000, that's 5 MB. For i=3, count ~3,333,333, etc. This may be okay. However there is a nuance: For i large, count is small. The total memory allocated across all primes might be large but they are freed after each iteration. However Python's memory allocation overhead might cause slowdown. But there is an alternative approach: Use a loop to set each multiple to 0 using slice assignment without creating a bytes object of that size? Actually the slice assignment expects a sequence of same length; we can use a memoryview? But not needed.
Another common pattern: is_prime[ii::i] = b'\x00' * ((n - ii)//i + 1) works.
I recall that for n=10^7, this sieve in Python completes within a second.
But there is a potential issue: In Python 3, the slice assignment for bytearray with step expects exactly the same number of elements, and the multiplication of bytes may be optimized using a buffer. It's fine.
Now, after building sizes, we need to answer queries. Since we have many queries (up to 2000), binary search each is fine.
But we could also precompute an array ans up to limit where ans[x] = max size ≤ x. This would be O(limit) which is 10M, which is fine, and then answering queries O(1). However that would require additional array of ints of size limit+1 (10M) -> about 80 MB if using Python list of ints (each int 28 bytes). That's too much. But we could use array('I') from array module to store 4-byte ints, which would be 40 MB, plus is_prime 10 MB = 50 MB. Might be acceptable but borderline. But binary search with a small list (maybe a few thousand entries) is efficient.
Let's estimate number of quadruplets up to 10M. Based on known data: The number of prime quadruplets up to 10^7 is about 198? Actually I can approximate using known counts: Up to 10^6, there are 46 quadruplets? Let's quickly compute: According to known sequences: A007530 (starting primes) values: up to 10^6: I think there are 46 quadruplets? I recall that up to 10^5 there are 12 quadruplets? Not sure. But likely less than 200. So sizes list length maybe ~200-300. So binary search is negligible.
Thus our plan is fine.
Now I'll write final code.
But we need to ensure we treat the case where limit may be less than 5? Not needed.
Now possible improvements: The sieve can be optimized by skipping even numbers. However for simplicity, I'll implement the standard bytearray sieve.
One more nuance: The prime 2 is prime; we need to mark multiples of 2, which will mark all even numbers >2 as not prime. That's fine.
But when we later check is_prime[a] for a=5,7,11,13 etc, they will be correctly set.
Now, test with small limit: limit=13, sieve:
is_prime[0]=0,1=0. Then for i in range(2,4): i=2: start=4, count=(13-4)//2+1= (9)//2+1=4+1=5? Actually (13-4)=9, //2 =4, +1=5, so assign 5 zeros to indices 4,6,8,10,12. That's correct. i=3: start=9, count=(13-9)//3+1=4//3+1=1+1=2? Actually (13-9)=4, //3=1, +1=2, assign zeros to 9,12 (but 12 already zero). So after that, primes: 2,3,5,7,11,13. Good.
Now check a=5: is_prime[5] true,7 true,11 true,13 true -> sizes.append(13).
Now we should confirm that for n=14, our output 13. Example says 13, correct.
Now code.
Potential pitfalls: When we read input, there may be many numbers. Using sys.stdin.read() and splitting is fine.
Now we should ensure we import bisect.
Now one more thought: The prime quadruplet might include the case where a=5 but also there is quadruplet starting with a=11? Yes.
Now verify if we need to consider quadruplets where a is negative? No.
Now I'll produce the final answer.
But I realize: The maximum size of quadruplet prime numbers whose size is n or less. That means we need to output the maximum a+8 such that a+8 ≤ n and (a, a+2, a+6, a+8) are all prime. That's what we compute.
Now double-check: For n=13, answer 13. For n=14, answer 13. For n=15,16,17,18 answer 13. For n=19 answer 19. That matches.
Now we should handle n=20 answer 19. Good.
Now confirm next after 19: size 109? Actually quadruplet (101,103,107,109) size 109. So for n=100, answer 19? Because max ≤100 is 19? Actually 109 >100, so max is 19. So for n=108, answer 19; for n=109, answer 109.
Now all good.
Now we must ensure that we include all quadruplets for all a up to limit-8. But what about a=5? Already included manually.
Now possible overflow: a+8 might be exactly limit. When we loop range(11, limit-7, 30), if limit-7 is inclusive? For limit=19, limit-7=12, range(11,12,30) yields 11, because start 11 <12, so includes 11. Then a+8=19, which is ≤ limit=19. Good. For limit=20, limit-7=13, range(11,13,30) includes 11 only. So includes 11, gives 19. Good.
Now for limit=21, limit-7=14, range(11,14,30) includes 11 only. So includes 19. But what about a=41? a+8=49, not prime. So fine.
Now for limit=109, limit-7=102, range(11,102,30) includes 11,41,71,101. a=101 yields 109 which is ≤109. So included.
Now for limit=108, limit-7=101, range(11,101,30) includes 11,41,71,101? 101 is not <101 because stop is 101 exclusive, so 101 is excluded. So a=101 not included, so we miss quadruplet with size 109 because 109 >108. That's correct as we only want sizes ≤ limit.
Now check a=5: we manually added if limit≥13. But for limit=108, we need size 13 and 19 only. So we must not add 109.
Now we need to be careful that a=5 quadruplet is added only if limit≥13, always. But for limit=108, 13 is valid. So it's added.
Now, but what if limit is less than 13? Not possible.
Now, is there any quadruplet with a=5 and a+8=13, but if limit=13, we add. Good.
Now, one more nuance: Could there be quadruplets with a=5 and a=11? Yes.
Now, are there any quadruplets with a=0? No.
Now, let's test for n=1e7, we will generate sizes list, then binary search.
Now, about the sieve: we could speed up by not marking even numbers >2 as prime. But let's keep simple.
Now we might need to treat the prime 2 specially, but it's fine.
Now check for limit up to 10 million, the sieve loop runs from 2 to sqrt(limit) ~3162. For each i, if is_prime[i], we do slice assignment. The total number of slice assignments is about number of primes up to 3162, which is about 447? That's fine.
Now, I'll produce final answer.
But wait: There's a potential issue: For large limit like 10M, the slice assignment for i=2 creates a bytes of size ~5M. For i=3, ~3.33M. For i=5, ~2M. For i=7, ~1.43M, etc. These allocations are large but not huge. However, there may be memory fragmentation but likely okay.
But there is a subtle bug: When we assign is_prime[start:stop:step] = b'\x00' * count, Python will try to assign the bytes to the slice. However, for bytearray, the slice assignment with step expects an iterable of the same length. If count is large, the multiplication might produce a bytes object of that length, but it's okay.
However, there is a known issue: In some Python implementations, the assignment of a very long bytes to a slice with a step may be slower, but still acceptable.
Alternatively, we could use a standard for loop for small i and slice for large i? But no need.
I'll go with this.
Now, after building sizes, we need to answer queries. Since queries are up to 2000, binary search each is fine.
Now final code:
import sys, math, bisect
def main():
data = sys.stdin.read().split()
if not data:
return
nums = list(map(int, data))
queries = []
for x in nums:
if x == 0:
break
queries.append(x)
if not queries:
return
code
max_n = max(queries)
limit = max_n
# Sieve
is_prime = bytearray(b'\x01') * (limit + 1)
is_prime[0] = 0
is_prime[1] = 0
sqrt_limit = int(limit**0.5) + 1
for i in range(2, sqrt_limit):
if is_prime[i]:
start = i*i
step = i
count = (limit - start) // step + 1
is_prime[start:limit+1:step] = b'\x00' * count
# Collect quadruplet sizes
sizes = []
if limit >= 13:
# Check (5,7,11,13) - they are primes always, but verify
if is_prime[5] and is_prime[7] and is_prime[11] and is_prime[13]:
sizes.append(13)
# else improbable, but just in case skip
# For a ≡ 11 mod 30, a >= 11
# Loop up to limit-8 inclusive
for a in range(11, limit - 7, 30):
# check if all four are prime
if is_prime[a] and is_prime[a+2] and is_prime[a+6] and is_prime[a+8]:
sizes.append(a+8)
# Note: sizes is already sorted increasing
out = []
for n in queries:
idx = bisect.bisect_right(sizes, n) - 1
out.append(str(sizes[idx]))
sys.stdout.write("\n".join(out))
if name == "main":
main()
But we need to verify that is_prime[5] etc are correctly set. Since we sieve up to limit, which may be as low as 13, then is_prime[5] is prime, yes.
Now test with the example manually by running mental simulation? Should work.
Now check for n=13: queries = [13]; limit=13; sieve up to 13; sizes includes 13. Then idx = bisect_right([13],13)-1 = 0, output 13.
Now n=14: queries include 14; limit=14? Actually max_n among queries would be 10000 in example, not 14. In our code we set limit = max(queries) which is 10000. So we sieve up to 10000, get all quadruplets up to 10000, sizes includes 13,19,109,...,9439. Then for query n=14, binary search finds 13. Good.
But we must ensure that for queries with n smaller than max_n, the binary search on the full sizes list (which includes sizes up to max_n) will correctly pick the largest ≤ n because the list contains all sizes up to max_n. So it's correct.
Now, what about when max_n is large (10 million) and there are many queries? We'll sieve once and then answer each query quickly.
Now, memory: is_prime = bytearray(limit+1). For limit=10M, 10,000,001 bytes ~ 10 MB. Python overhead for bytearray is minimal. sizes list maybe few thousand entries.
Now, potential speed: The sieve loop from 2 to sqrt_limit (3162) with slice assignments may be okay. However I recall that slice assignment for bytearray with step may be slower than using memoryview? But still acceptable.
We can micro-opt: For i=2, we can treat separately and use is_prime[4::2] = b'\x00'*((limit-4)//2+1) but same.
We can also skip marking for even numbers by starting from i=3 and step=2. But not necessary.
One more nuance: In Python, the expression b'\x00' * count creates a bytes object of length count. For count large, it may take some time to allocate and fill. But that's okay.
Another approach: Use is_prime[start:limit+1:step] = b'\x00' * ((limit - start)//step + 1) is common.
Now, I'd like to test performance on a typical environment. But I cannot run here.
Potential pitfalls: For limit=10,000,000, the slice assignment for i=2 will create a bytes object of size about 5,000,000, which is 5 MB. That's fine.
But we must ensure that we use integer arithmetic and not float for sqrt. We used int(limit**0.5) + 1. That's okay.
Now, for limit=10 million, limit**0.5 is computed as math.sqrt? It's okay.
Now, we need to include import bisect.
Now, maybe we can also precompute the list of quadruplets using known pattern and precomputed primes. But our sieve is fine.
Now, think about possible memory/performance improvements: The sieve can be made faster by only considering odd numbers. But I think it's acceptable.
MAX_N = max(queries) if queries else 0
# But the problem statement says n ≤ 10,000,000, but maybe test cases have smaller max. To be safe, we can compute up to 10,000,000 anyway. However if MAX_N is less than 13? Not possible. But if MAX_N is less than 13? But queries are ≥13 except maybe 0. So fine.
# We'll set LIMIT = 10_000_000 # constant as per problem.
LIMIT = 10_000_000
# Actually we need to sieve up to LIMIT (10 million). But if MAX_N is less than LIMIT, we could limit sieve to MAX_N to be faster. Since there might be many test cases with small n? Possibly but not many? The number of datasets ≤2000. So we can compute up to the maximum n among queries. That would reduce work if max is small. But worst-case max_n=10M, same. So I'll compute up to max_n (but at least maybe 13). However note: when we collect quadruplets, we need to include all sizes up to max_n. So we can set LIMIT = max(queries). But careful: The quadruplet size must be ≤ n. For query with n smaller than max_n, we only need sizes ≤ max_n. So it's okay. But what if later queries have larger n? Actually we compute based on the max among all queries. So we set limit = max(queries) (since all queries are known upfront). That's efficient.
# However if we have only one query with n=13, we sieve up to 13? That would require primes up to 13 to test quadruplets? For a=5, we need to check primes 5,7,11,13. That's fine. For a=11 (which gives size 19 >13), we don't need it because we only need sizes ≤13. But we do need to check if there is any quadruplet with size ≤13, which is only a=5. So we could sieve only up to 13. However for general case, we might need to check candidate a up to limit-8. So we can set limit = max(queries). But we also need to check primality of numbers up to limit. So we sieve up to limit.
# But also note: For checking a=5, we need prime up to 13. So limit must be at least 13.
# So I'll set limit = max(queries). However, for binary search we need the list of sizes up to max(queries). So that's fine.
# But what if max(queries) is less than 19? Then sizes list will only contain 13 maybe. So fine.
# However careful: The prime checking for candidate a may require checking a+8 which might be up to limit. So we need to ensure limit >= a+8. So for a in candidate loop, we only consider a where a+8 <= limit. So we iterate a up to limit-8. So limit should be max(queries). That's fine.
# But what about quadruplets whose size is less than max(queries) but a+6 maybe > max(queries)? Actually size is a+8. If a+8 ≤ max(queries), then a+6 ≤ a+8 -2 ≤ max(queries)-2, which is ≤ max(queries) and we need to check primality of a+6. So we need to have prime check up to max(queries) as well. So sieving up to max(queries) is enough.
# So we can set limit = max(queries). But we must also consider the special case a=5: size=13. If max(queries) <13? But queries are >=13, so limit >=13.
# However if max(queries) is small like 13, we sieve up to 13, which is trivial.
# Thus I'll use limit = max(queries) to be efficient.
# But note: The problem may give queries with n up to 10,000,000. So in worst-case limit=10M anyway.
# Edge: if there are no queries (only 0)? Then we exit.
# Implementation:
if not queries:
return
limit = max(queries)
# Sieve
is_prime = bytearray(b'\x01') * (limit + 1)
is_prime[0] = 0
is_prime[1] = 0
import math
sqrt_limit = int(limit ** 0.5) + 1
for i in range(2, sqrt_limit):
if is_prime[i]:
step = i
start = i*i
# Compute count: (limit - start)//step + 1
count = (limit - start) // step + 1
is_prime[start:limit+1:step] = b'\x00' * count
# Build sizes list
sizes = []
# Check a=5 if limit >=13
if limit >= 13:
# Check 5,7,11,13 are prime
if is_prime[5] and is_prime[7] and is_prime[11] and is_prime[13]:
sizes.append(13)
else:
# They are primes always but just in case.
pass
# For a from 11 to limit-8 step 30
# Use range(11, limit-7, 30) because limit-8 inclusive.
for a in range(11, limit - 7, 30):
# Check a+8 <= limit? Since we set limit-7 exclusive, the largest a is <= limit-8, so a+8 <= limit.
if is_prime[a] and is_prime[a+2] and is_prime[a+6] and is_prime[a+8]:
sizes.append(a+8)
# sizes are sorted increasing.
# Answer queries
out_lines = []
for n in queries:
# binary search
idx = bisect.bisect_right(sizes, n) - 1
out_lines.append(str(sizes[idx]))
sys.stdout.write("\n".join(out_lines))