HackerRank Strange Counter
Style

In C++, don't #include&lt;stdio.h&gt; or any other C-style .h file.  #include &lt;iostream&gt; should be sufficient for all of your I/O needs.  It is customary to put a space after #include.

In general, using namespace std is bad practice.  Here, you actually wasted more characters writing the "shortcut" than writing out std::cin and std::cout like you should have.

In the problem statement, the input is called t.  Why did you name your variable n in your code then?

x is a cryptic variable name.  I suggest countdown_init.

It is customary to end the output with a newline.  If you don't, then in Unix shells the command prompt would immediately follow the output on the same line, which looks ugly.

Algorithm

The reason your program exceeds the time limit is simple: this loop counts up to n, one step at a time.


for(long long i = 2; i &lt;= n;i++)



Your algorithm is thus said to be O(t).

To speed it up, you need to fast-forward through entire countdown sequences.

#include &lt;iostream&gt;

int main() {
    long long countdown_init, t;
    std::cin &gt;&gt; t;
    for (countdown_init = 3; t &gt; countdown_init; countdown_init *= 2) {
        t -= countdown_init;
    }
    std::cout &lt;&lt; (countdown_init - t + 1) &lt;&lt; '\n';
}


This solution would be O(log t), since it only loops once per countdown cycle.  We can estimate the amount of work by rounding up t to the last t of each cycle:

$$\begin{align}
t \approx&amp;\ 3\ (\underbrace{1 + 2 + 4 + \ldots + 2^{c}}_{c\ \textrm{cycles}}) \\
  \approx&amp;\ 3 \cdot 2^{c+1} \\
  =&amp;\ 6 \cdot 2^c
\end{align}$$

The number of cycles \$c\$ is therefore

$$c \approx \log_2 \frac{t}{6} = O(\log t)$$