0
$\begingroup$

$4, 2, 4, 2, 4, 6, 2, 6,$ then repeat.

I'm having difficulty coming up with the general term. This is part of a program I'm writing, so a recursive definition would be fine. I'd prefer to keep track of at most one auxiliary variable though.

EDIT

So here's a solution for the different sequence $2,4,2,4,2,4,2,4,\ldots$ that I sort of want to parallel:

$a_0=2$ and $a_{i+1}=a_i+(-1)^i2$

Implemented in code, I would export the term $(-1)^i$ to another variable and at each iteration multiply it by $-1$.

$\endgroup$
  • $\begingroup$ I'm not a programmer so feel free to tell me if this is a stupid suggestion, but I would have thought you could give a lookup table for the first eight values and then $a(n)=a(n\,{\rm mod}\,8)$ for the rest. $\endgroup$ – David Feb 26 '14 at 6:20
  • $\begingroup$ It's cheap to provide the space for the lookup table, but constant look-ups and modular arithmetic isn't the best thing to do. It also lacks a certain 'beauty'. I just feel like there has to be a simple pattern to this sequence. $\endgroup$ – Robert Wolfe Feb 26 '14 at 6:27
  • 3
    $\begingroup$ @Bryan: Why is it not the best thing to do? (By the way, as $8$ is a power of two, $n \bmod 8$ is just n & 7 in code (this means zeroing out all but the last three bits); it gets compiled to a single bitwise instruction AFAIK.) $\endgroup$ – ShreevatsaR Feb 26 '14 at 7:30
2
$\begingroup$

$$\eqalign{a_n &= {\frac {15}{4}}+ \left( 1-\dfrac{\sqrt {2}}{4} \right) \cos \left( \pi \,n/4 \right) + \left( 1+\dfrac{\sqrt {2}}{4} \right) \cos \left( 3\pi \,n/4 \right) +\dfrac{1}{4}\,\cos \left( \pi \,n \right) \cr&+ \left( -1+\dfrac{\sqrt {2}}{4} \right) \sin \left( \pi \,n /4\right) +\dfrac12\,\sin \left( \pi \,n/2 \right) + \left( 1+\dfrac{\sqrt {2}}{4} \right) \sin \left( 3\,\pi \,n/4 \right) \cr} $$ will do if you want something like that. But the solution of taking $n \mod 8$ is much better practically.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.