# Writing code to produce continued fractions

I have been trying to create a continuing fraction to help prove the theory about any rational number: a/b being able to be written as a continued fraction where the remainders found in the Euclidean Algorithm are used as the coefficients. Before I can properly implement that theory, I am trying to use a loop to create a continuing fraction using a basic set of numbers. Here is what I have below:

set = {1, 2, 3, 4, 5};
Len = Length[set];
Frac = 0;
For[i=1, i<=Len, i++, Frac = 1/(Frac+set[[i]])]
Print[Frac]


When I put the projected continuous fraction into Wolfram Alpha: (1/(1+(1/2)+(1/(1/3))+(1/1/(1/4))+(1/1/1/(1/5)))), the result was 2/27.

However my code returns a completely different number. What do I need to do differently in my for loop to return the right answer? I have seen the other abstract code for Mathematica involving continued fractions and it makes no sense to me. I also need to submit legible code for my final project.

I think both your code and your Wolfram|Alpha query gave the wrong answer. Here is how I would write a function to generate a rational value from a list of continued fraction terms.

fromTerms[terms_List] := Fold[#2 + 1/#1 &, Reverse @ terms]


This is nice, concise, functional code and

set = {1, 2, 3, 4, 5};
fromTerms[set]


gives

225/157

which we can demonstrate to be correct by giving set to the built-in function FromContinuedFraction.

FromContinuedFraction[set]


225/157

My version of procedural code to perform the computation is:

proceduralFromTerms[terms_List] :=
Module[{frac = terms[[-1]]},
Do[frac = terms[[i]] + 1/frac, {i, -2, -Length[terms], -1}];
frac]


Given set, this produces the same result as FromContinuedFraction.

Note that fromTerms cam be used to produce symbolic approximations to continued fractions.

fromTerms[Array[x, 5]] 