#K6706. Longest Prime Row

    ID: 32558 Type: Default 1000ms 256MiB

Longest Prime Row

Longest Prime Row

You are given an integer n representing the total number of books labeled from 1 to n. Starting with the book labeled 1, you must form the longest possible row of books by repeatedly adding a prime number to the last book's label such that the result does not exceed n and the book has not already been selected. In other words, if the current book label is x and p is a prime number, you can choose x+p as the next book in the row if x+p ≤ n. The process stops when no prime number can be added without exceeding n.

Your task is to output the length of the obtained sequence and the sequence itself. Note that the strategy is greedy: at each step, select the smallest prime that yields a valid new book, ensuring the row is as long as possible.

Examples:

  • For n = 10, one valid answer is 5 with the sequence: 1 3 5 7 9.
  • For n = 15, one valid answer is 8 with the sequence: 1 3 5 7 9 11 13 15.
  • For n = 1, the only possible sequence is just 1.

Note: The tests will only check that the returned sequence’s length meets a specific minimum and that all its elements belong to the range [1, n].

inputFormat

The input consists of a single integer n (read from standard input).

Example:

10

outputFormat

The first line of output should be the length k of the sequence. The second line should contain the k numbers of the sequence, separated by a single space (written to standard output).

Example:

5
1 3 5 7 9
## sample
10
5

1 3 5 7 9

</p>