Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:
$$ a_0 +\cfrac 1 {a_1 + \cfrac 1 {a_2 + \cfrac 1 {\ddots + \cfrac 1 {a_n} } } } $$
Or they can be represented as a list of values: \$[a_0 ; a_1, a_2, \dots, a_n]\$
The challenge:
take a base number: \$a_0\$ and a list of denominator values: \$[a_1, a_2, \dots, a_n]\$ and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.
Examples:
- \$\sqrt 19\$:
[4;2,1,3,1,2]: 170/39
- \$e\$:
[1;0,1,1,2,1,1]: 19/7
- \$\pi\$:
[3;7,15,1,292,1]: 104348/33215
- \$ϕ\$:
[1;1,1,1,1,1]: 13/8
Example implementation: (python)
def foo(base, sequence):
numerator = 1
denominator = sequence[-1]
for d in sequence[-2::-1]:
temp = denominator
denominator = d * denominator + numerator
numerator = temp
return numerator + base * denominator, denominator
2.002
can be expressed as2002/1000
. That's technically a "single fraction", you probably want to say, "a single fraction, in its most simple form." \$\endgroup\$