#P1467. Cyclic Numbers

    ID: 14753 Type: Default 1000ms 256MiB

Cyclic Numbers

Cyclic Numbers

A cyclic number is an integer that does not contain the digit $0$ and has no repeated digits, and it also satisfies the following interesting property:

Let the number be represented by its digits $d_1d_2\ldots d_n$. Starting from the leftmost digit $d_1$, count forward $d_1$ digits in a circular manner (wrapping around to the front when necessary) to obtain a new digit. Then, from that digit, count forward by its value to obtain the next digit, and repeat this process. If after exactly $n$ steps each digit has been visited once and the process returns to $d_1$, then the number is said to be cyclic. Otherwise, it is not.

For example, consider the number 81362:

  • Start at 8. Counting 8 digits circularly: 1, 3, 6, 2, 8, 1, 3, 6 → landing on 6.
  • From 6, count 6 digits: 2, 8, 1, 3, 6, 2 → landing on 2.
  • From 2, count 2 digits: 8, 1 → landing on 1.
  • From 1, count 1 digit: 3 → landing on 3.
  • From 3, count 3 digits: 6, 2, 8 → landing back on 8.

Since every digit is visited exactly once before returning to the starting digit, 81362 is cyclic.

Given an integer $m$, find the first cyclic number greater than $m$. It is guaranteed that the answer fits in an unsigned 32-bit integer, i.e. in the range $[0,2^{32})$.

inputFormat

The input consists of a single integer $m$.

outputFormat

Output the smallest cyclic number greater than $m$.

sample

1
2