Prime-Free Sequence
Time limit1sMemory limit128 MB
Find the lexicographically smallest permutation of n..m where sums of any 2 to d consecutive numbers are all non-prime, or report none.
- Level
Medium7 of 10
- Topics
- Backtracking, DFS, Number theory, Greedy
- Solved
- No attempts yet
Problem
Consider the sequence of consecutive integers from to . By rearranging these numbers appropriately, you can make the sum of every two adjacent numbers non-prime; a sequence arranged this way is called a prime-free sequence.
For example, when and , the arrangement 1, 3, 5, 4, 2, 6, 9, 7, 8, 10 is one prime-free sequence, and it is the lexicographically smallest among all of them.
Extending this idea, a -th order prime-free sequence is a sequence in which the sum of every consecutive numbers is non-prime. The sequence above is a nd order prime-free sequence, because the sum of each pair of adjacent numbers is non-prime. It is not a rd order prime-free sequence, however, because the three consecutive numbers 5, 4, 2 sum to 11, which is prime. For and , the lexicographically smallest rd order prime-free sequence is 1, 3, 5, 4, 6, 2, 10, 8, 7, 9.
Given , , and , write a program that finds the lexicographically smallest -th order prime-free sequence.
Input
The input consists of several test cases. Each test case is a single line containing three integers , , and separated by spaces, satisfying and .
The last line of the input contains and must not be processed.
Output
For each test case, print the -th order prime-free sequence on one line, with the numbers separated by commas (,). If more than one such sequence exists, print the lexicographically smallest one (the sequence whose first number is smallest; if tied, whose second number is smallest; and so on).
If no -th order prime-free sequence exists, print No anti-prime sequence exists.