Aronson's Sequence

Time limit2sMemory limit128 MB

Summary
Compute terms of Aronson's sequence, where each term is the position of the k-th letter T in the self-referential sentence listing those positions as ordinals.
Level

Medium6 of 10

Topics
Simulation, Implementation
Solved
No attempts yet

Problem

Aronson's sequence aka_k is defined by the self-referential sentence:

"T is the first, fourth, eleventh, ... letter of this sentence."

The blanks (...) are filled in so that the sentence describes itself truthfully. Read the sentence and count only letters (spaces, punctuation, and digits are ignored, and case is ignored). Then aka_k is the position of the kk-th occurrence of the letter T. The first few values are:

1, 4, 11, 16, 24, 29, 33, 35, 39, …1,\ 4,\ 11,\ 16,\ 24,\ 29,\ 33,\ 35,\ 39,\ \dots

For k≤100000k \le 100000 it can be shown that ak≤1000000a_k \le 1000000.

To build the sentence you must spell ordinal numbers in English. Ordinals (first, second, third, …) are defined from the cardinals (one, two, three, …), so the cardinals are described first.

  • A cardinal below twenty is a single word (3 → three, 17 → seventeen).
  • A cardinal from twenty to ninety-nine is the tens word, followed by the nonzero ones word (40 → forty, 56 → fifty six).
  • A cardinal from one hundred to nine hundred ninety-nine is the hundreds part, followed by the nonzero remainder (100 → one hundred, 117 → one hundred seventeen, 640 → six hundred forty, 999 → nine hundred ninety nine).
  • A cardinal from one thousand to nine hundred ninety-nine thousand nine hundred ninety-nine is the thousands part, followed by the nonzero remainder (12345 → twelve thousand three hundred forty five).

An ordinal is written like its cardinal, but the last word is turned into its ordinal form:

3rd → third, 56th → fifty sixth, 100th → one hundredth, 12345th → twelve thousand three hundred forty fifth.

Input

The input contains several queries. Each query is a positive integer kk on its own line (1≤k≤1000001 \le k \le 100000). The queries are given in non-decreasing order. The input ends with a line containing a single 0.

Output

For each query kk, print aka_k on its own line. Every aka_k is at most 10000001000000.

Examples1

  1. Example 1

    Input
    1
    3
    9
    0
    
    Expected output
    1
    11
    39