How to solve this mathematically

82 Views Asked by At

This is a question given in my computer science class. We are given a global variable $5$. Then we are to use keyboard event handlers to do the following:

On event keydown double the variable and on event keyup subtract $3$ from this variable.

The question is after $12$ presses of any key on the keyboard ( a keydown and keyup event is the same as one press), what will be the value of this variable? The value after $ 4$ presses is $35$.

I can implement this and get the answer in less than 10 lines of code, but this is one of those questions I feel there should be a mathematical formula one can derive and apply to the question and arrive at an answer. So is it possible to solve this one with math?

I already tried: $\lim\limits_{x \to 12} (2v - 3)x$ where $v$ is the initial variable and I am trying to represent an equation that will evaluate to the new value of the variable as $x$ gets to $12$. However since I am not very mathematically minded, that was as far as I got.

Thanks

2

There are 2 best solutions below

4
On BEST ANSWER

You can express this as a recurrence relation $a_n = 2 a_{n-1} - 3$ with initial condition $a_0 = 5$. To find a closed form, divide both sides by $2^n$ to get $$ \frac{a_n}{2^n} = \frac{a_{n-1}}{2^{n-1}} - \frac{3}{2^n}. $$

Let $s_n = a_n \cdot 2^{-n}$. This gives $s_n = s_{n-1} - 3 \cdot 2^{-n}$. Hence $s_n = -3 \sum_{j=1}^n 2^{-k} + a_0$. This is a geometric series with closed form $s_n = 3 \cdot 2^{-n} + a_0 - 3$. We conclude that $$ a_n = (a_0 - 3) 2^n + 3. $$

For $a_0 = 5$, this gives $a_4 = 35$.

0
On

Limits are way more power than necessary.

Assuming $x_0$ is really $5$, we're looking at the recurrence \begin{gather*} x_0=5 \\[0.3ex] x_{n+1}=2x_n-3. \end{gather*}

The steady state is $x=2x-3\implies x=3$, suggesting we write $$x_{n+1}-3=2(x_n-3),$$ which implies giving $x_n-3=(x_0-3) 2^n$, or $$x_n=3+(5-2)\cdot 2^n=3+2^{n+1}$$