#CCC23S5. The Filter

The Filter

Canadian Computing Competition: 2023 Stage 1, Senior #5

Alice, the mathematician, likes to study real numbers that are between 0 and 1. Her favourite tool is the ​filter​.

A filter covers part of the number line. When a number reaches a filter, two events can happen. If a number is not covered by the filter, the number will pass through. If a number is covered, the number will be removed.

Alice has infinitely many filters. Her first 3 filters look like this:

In general, the k-th filter can be defined as follows:

  • Consider the number line from 0 to 1.
  • Split this number line into 3k3^k equal-sized pieces. There are 3k+13^k+1 points and 3k3^k intervals.
  • The k-th filter consists of the 2nd interval, 5th interval, 8th interval, and in general, the (3i1)th(3i−1)^{th} interval. The points are not part of the k-th filter.

Alice has instructions for constructing the ​Cantor set​. Start with the number line from 0 to 1. Apply all filters on the number line, and remove the numbers that are covered. The remaining numbers form the Cantor set.

Alice wants to research the Cantor set, and she came to you for help. Given an integer N, Alice would like to know which fractions x/Nx/N are in the Cantor set.

Input Specification

The first line contains the integer N.

The following table shows how the available 15 marks are distributed:

Marks Awarded Bounds on N Additional Constraints
3 marks 3≤N≤318 N is a power of 3
4 marks 2≤N≤105 None
8 marks 2≤N≤109

Output Specification

Output all integers x where 0≤x≤N and x/Nx/N is in the Cantor set.

Output the answers in increasing order. The number of answers will not exceed 106.

Sample Input

12

Output for Sample Input

0
1
3
4
8
9
11
12

Explanation of Sample Output

Here is a diagram of the fractions and the first 4 filters. In reality, there are infinitely many filters.

512, 612, and 712 are not in the Cantor set because they were covered by the 1st filter.

Furthermore, 212 and 1012 are not in the Cantor set because they were covered by the 2nd filter.

It can be shown that the remaining fractions will pass through all filters.