How can I write Mathematica code for this continued fraction with alternating terms?
You can use ContinuedFractionK[]
for this:
φ + ContinuedFractionK[1, φ^(1 - 2 Boole[Mod[k, 2] == 1]), {k, n}]
Greg Martin suggests the simpler expression
φ + ContinuedFractionK[1, φ^((-1)^k), {k, n}]
An exercise for the motivated reader is to prove that this is equivalent to the simpler
(Fibonacci[n + 2] φ)/Fibonacci[n + 1]
z = Defer /@ {-1, ""};
φ + Nest[1/(φ^Last[z = RotateLeft[z]] + #) &, …, 5]
z = Defer /@ {Style[-1, 14], ""};
Style[φ + Nest[1/(φ^Last[z = RotateLeft@z] + #) &, …, 5], 32, ScriptSizeMultipliers -> 1]
Alternatively,
z = φ^(Defer /@ {Style[-1, 14], ""});
i = 1;
Style[φ + Nest[1/(z[[Mod[i++, 2, 1]]] + #) &, …, 5], 32, ScriptSizeMultipliers -> 1]
You can use Fold[]
for this (an example from Documentation Center):
ϕ + Fold[1/(#2 + #1) &, ϕ, Reverse[Table[ϕ^(1 - 2 Boole[Mod[k, 2] == 1]), {k, 1, 7}]]]