4 of 6
added 6 characters in body
MickyT
  • 12.2k
  • 2
  • 25
  • 48

T-SQL, 229 227 138

Been a while since I did an SQL answer and as always it's very verbose. Edit Of course I over complicated it and didn't need a recursive query at all.

CREATE FUNCTION A(@ INT)RETURNS TABLE RETURN SELECT'$$\varphi=1+\'+REPLICATE('cfrac1{1+\',@)+IIF(@>0,'d','')+'dots'+REPLICATE('}',@)+'$$'S

Original

CREATE FUNCTION A(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT CAST('$$\varphi=1+\dots'AS VARCHAR(MAX))S,0N UNION ALL SELECT REPLACE(STUFF(S,14,0,'cfrac1{1+\'),'\do','\ddo')+'}',N+1FROM R WHERE N<=@)SELECT S+'$$'S FROM R WHERE N=@

This creates an inline table function that uses a recursive query to stuff in the additional cfrac1{1+\ per iteration. Changing the dots to ddots was expensive, but saved a couple getting rid of the replace :). Also having to cast the original string as 'VARCHAR(MAX)' cost a bit.

It's used as follows SQLFiddle:

SELECT * 
FROM (SELECT N FROM(VALUES(0),(1),(2),(3),(4),(5))A(N)) N
    CROSS APPLY A(N.N)
N   S
--- ---------------------------------------------------------------------------
0   $$\varphi=1+\dots$$
1   $$\varphi=1+\cfrac1{1+\ddots}$$
2   $$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$
3   $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$
4   $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$
5   $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}}$$

N=0 $$\varphi=1+\dots$$

N=5 $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}}$$

MickyT
  • 12.2k
  • 2
  • 25
  • 48