1

You start with an integer $n$. Repeat the following process $i$ times:

$n=$ $n+\text{the reverse of n} $

By 'reverse' I mean the digits of the number are flipped, ie $123 \rightarrow 321$.

Is there a general formula for the eventual result in terms of $n$ and $i$? I've tried expressing it more mathematically to try to get an answer, but 'reversing digits' doesn't seem to be something expressable as a formula.

Nico A
  • 5,064

1 Answers1

0

This is a simple recursive algorithm:

// Precondition: n >= 0
// Postcondition: n with its digits reversed
int reverse(int n)
{
    if (n < 10) {
        return n;
    } else {
        int last_digit = n % 10;
        int ten_power  = pow(10, (int)log10(n));
        return last_digit * ten_power + reverse(n/10);
    }  
}

So, reverse(123456) returns $654321$.

If $n \geq 0$, the formula may be written as $$\mathrm{rev}(n) = \begin{cases} n,&\text{if }n < 10\\ k\cdot 10^{\lceil\log_{10}(n)\rceil} + \textrm{rev}(\lfloor n/10\rfloor),&\text{otherwise} \end{cases}$$ where $k$ is the last digit of $n$. That is, $k$ is the remainder of $n/10$, or equivalently, $$k = n - 10 \lfloor \frac{n}{10} \rfloor$$

JnxF
  • 1,277
  • So how can I apply this to solve my question mathematically? – Nico A Jul 20 '16 at 15:33
  • This is just a hint to your problem with the "reversing digits" part. I think you wouldn't go much further with this recursive formula, but it is an idea. – JnxF Jul 20 '16 at 15:39