# Generate MathJax for the Golden Ratio Continued Fraction

In anticipation of MathJax being temporarily disabled, the rendered MathJax in this question has been replaced with images. You are still welcome to post answers but you'll have to view the rendered MathJax on another site.

PPCG just got MathJax! This means we can now easily include well formatted mathematical formulas into posts. (Handy MathJax tutorial.)

For example, here is the golden ratio expressed as an infinite continued fraction: The MathJax code for this equation is

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

You can find this by right clicking the formula and following Show Math AsTeX Commands.
The $$ means it is displayed on its own in the center of the page instead of inline. Use a single  for inline. # Challenge Write a program that takes in a non-negative integer, n, and outputs the MathJax code for that many "steps" of the continued fraction for the golden ratio. To keep things standard across answers, you must use this exact MathJax syntax: • For n = 0, the output must be $$\varphi=1+\dots$$. Which is rendered as: • For n = 1, the output must be $$\varphi=1+\cfrac1{1+\ddots}$$. Which is rendered as: • For n = 2, the output must be $$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$. Which is rendered as: • For n = 3, the output must be $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$. Which is rendered as: This pattern continues on for larger n. You could say that n represents the number of division lines in the equation. ### Notes • \cfrac is used instead of the more common \frac. • \dots is used instead of \ddots for n = 0. • Take input from stdin or the command line. • Output to stdout (with an optional trailing newline). • Alternatively, you may write a function that takes in n as an integer and returns the MathJax code as a string (or still prints it). # Scoring The smallest submission in bytes wins. Tiebreaker goes to the earlier submission. • Just a note to those wanting to run the stack snippet: Like many (most?) stack snippets, this doesn't work in Safari. – Alex A. Apr 8 '15 at 0:53 • The stack snippet doesn't work when you type stuff... it gives Uncaught ReferenceError: textbox is not defined – soktinpk Apr 8 '15 at 2:50 • @soktinpk That's strange, I'm having the same problem. But the snippet over here works even though it's the exact same... Here's an external byte counter in case. – Calvin's Hobbies Apr 8 '15 at 2:57 • MathJax has been reenabled for PPCG! – wastl Jul 10 '18 at 13:53 ## 16 Answers # CJam, 51 50 bytes $$\varphi=1+""\cfrac1{1+"ri:R*'\"ddots"R!>'}R*'$_  Code explanation: "$$\varphi=1+" "This is a static string"; "\cfrac1{1+"ri:R*'\ "Repeat this string input number times. Put a \ at the end"; "ddots"R!> "If input is 0, remove 1st characters, else not"; '}R* "Put the closing bracket R times"; '_ "The final$$";  Few examples: N = 0 $$\varphi=1+\dots$$  N = 4 $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$  N = 15 $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}}}}}}}}}}}}$$  UPDATE - 1 byte saved thanks to Sp3000! Try it online here • A little shuffling gives 50: "$$\varphi=1+""\cfrac1{1+"ri:R*'\"ddots"R!>'}R*'_ – Sp3000 Apr 8 '15 at 9:14 • I didn't look at your answer at all - just coincidence. Either way, your 49 byte Pyth solution is 50 bytes in reality, because you have to escape \v to \\v. – orlp Apr 8 '15 at 11:49 • @orlp and that is why I rolled back as there was no potential benefit in that solution being present here as well. – Optimizer Apr 8 '15 at 12:20 # Python, 7068 67 bytes lambda n:"$$\\varphi=1+\%sdots%s$$"%("cfrac1{1+\\"*n+"d"[:n],"}"*n)  This defines an anonymous function which just uses simple string multiplication and string formatting. (Thanks to @xnor for pointing out that \\c can just be written as \c, since c can't be escaped. Unfortunately this doesn't hold true for \\v, since \v is ASCII 11.) Previous attempts: lambda n:"$$\\varphi="+"1+\\cfrac1{"*n+"1+\\"+"ddots"[n<1:]+"}"*n+"$$" lambda n:r"$$\varphi=%s1+\%s$$"%("1+\cfrac1{"*n,"ddots"[n<1:]+"}"*n)  • You beat me by 14 seconds! Also 70 chars. – xnor Apr 8 '15 at 1:21 • I think this works without using a double \ before cfrac. – xnor Apr 8 '15 at 1:29 • @xnor Seems like it, thanks! And sorry for taking the Python golfs all the time... – Sp3000 Apr 8 '15 at 1:33 • Nah, I've stolen my fair share of races to post from you. – xnor Apr 8 '15 at 1:34 # ><>, 89 86 + 3 = 89 bytes :&"$$"{\l?!;o70. }-1v!?:<{"}" &:&\~"stod"&:&?: {1->:?!v}"\+1{1carfc" rav$"\~"\+1=ihp  Run with the -v flag, e.g. py -3 fish.py program.fish -v 3  Surprisingly ><> doesn't do too badly here, since we can mimic string multiplication by having a counter which we decrement every iteration. :&""{\ Put n into the register and push "" }-1v!?:<{"}" Push n "}"s &:&\~"stod"&:&?: Push "stod", and copy the final "d" if n != 0 {1->:?!v}"\+1{1carfc" Push n "\+1{1carfc"s rav$$"\~"\+1=ihp            Push "\+1=ihprav$" \l?!;o70. Keep printing chars until the stack is empty  (-3 bytes thanks to @randomra) • Two small improvements for 3 bytes (at the end of line 1 and line 3): pastebin.com/wEbKhuUH – randomra Apr 8 '15 at 5:53 • Hah the first and last line mirrors match up, didn't notice :P – Sp3000 Apr 8 '15 at 6:08 # Retina, 160 + 7 = 167 bytes ;.+ \varphi=1+\dots#0  ;+(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0) 11111111112345678910# ;# ;+\\d?dots\d(\d*) \cfrac1{1+\ddots1}  Each line goes into a separate source file, so I've added 1 byte for each file after the first. However, for convenience, Retina now also supports the -s command-line flag, which allows you to put all of this into a single file (in which case the newlines are treated as file separators). The largest part of the code (98 bytes) is used to convert the input from decimal to unary (files 3 to 6). The basic idea of the code is to surround the input in \varphi=1+\dots..., then convert the input to unary, and then expand \dotsN or \ddotsN to the next level of the continued fraction (while reducing N to N-1). # Julia, 76 73 bytes n->("$$\\varphi=1+"*"\\cfrac1{1+"^n*"\\"*"d"^(n>0)*"dots"*"}"^n*"$$")  This creates a lambda function that takes a single integer as input and returns the MathJax as a string. To call it, give it a name, e.g. f=n->.... Unfortunately both backslashes and dollar signs have to be escaped in Julia strings because they both have special meaning. String concatenation is performed using * and string repetition with ^. Examples: julia> f(0) "\varphi=1+\dots" julia> f(4) "\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}"  Suggestions are welcome as always! Edit: Saved 3 bytes thanks to plannapus! • "d"^(n>0) instead of (n>0?"d":"") would make it shorter. – plannapus Apr 8 '15 at 8:39 • @plannapus: I don't understand what your name means but you're a genius! I had forgotten that "string"^0 was legit. – Alex A. Apr 8 '15 at 20:24 • you're welcome. My pseudonym is the name of a radiolarian genus, being myself a radiolarian paleontologist. It translates to "flattened turnip" i think :) – plannapus Apr 9 '15 at 6:07 • I am waiting for a BF answer=) – flawr Apr 9 '15 at 9:06 • @flawr: I hope you're not waiting on me for that... – Alex A. Apr 10 '15 at 4:27 # Element, 63 Chars _+2:'$$\\varphi\=1\+[\\cfrac1\{1\+]?\\[d.]"dots[\}]$$  This is the most straight-forward solution. Unfortunately, the large amount of symbols in the output causes a significant increase in program length (putting the strings in the program directly causes the symbols to perform operations). I'm sure there is room for golfing, but I don't have more time right now. Since this language is still relatively unknown, here is a link to the interpreter, written in Perl. _+2: take input, add 0 to it to make it a number, and duplicate ' put one copy onto the control stack$$\\varphi\=1\+ a "bare" string  output the string [ start a for loop, based on the input from earlier \\cfrac1\{1\+ a bare string  output it ] end the for loop ? test the second copy of the input for non-zero-ness \\ a bare \ [d.] a "for" loop used as an if block, appends a "d"  output it dots output dots " get rid of the if condition result so the old result is on top [ another for loop, still using the input from earlier \} output a } ] end for loop$\$ output $$ • +1 for using Element! It's time for Element to become a household name! – Alex A. Apr 8 '15 at 20:45 # T-SQL, 229227 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}}}}}$$ # Ruby, 767571 70 bytes This feels suspiciously straightforward, so please let me know if I messed up somewhere. Incidentally, this is the first thing I've ever written in Ruby - I was looking for a language that supported string repetition by multiplying, and Ruby seemed to do the trick. f=proc{|n|'$$\varphi=1+'+'\cfrac1{1+'*n+'\dd'[0,n+2]+'ots'+'}'*n+'$$'}  To be applied like so: f.call(0)$$\varphi=1+\dots$$f.call(3)$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$ • @Sp3000 The former doesn't, since Ruby apparently can't convert Booleans to integers. The latter worked though, so thanks for that! – vvye Apr 8 '15 at 14:00 # J, 60 bytes (<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$');@#~1,~51,],*  Usage:  ((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$');@#~1,~51,],*) 0$$\varphi=1+\dots$$((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$');@#~1,~51,],*) 3$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$ Method: The string '$$\varphi=1+\ cfrac1{1+\ d dots } $$' is cut up at spaces and the parts are repeated 1 n signum(n) 1 n 1 times and then these parts are concatenated. Try it online here. # R, 93 90 Much the same as the other answers. Thanks to @plannapus for the scan tip. cat('$$\\varphi=1+\\',rep('cfrac1{1+\\',n<-scan()),if(n)'d','dots',rep('}',n),'$$',sep='')  cat used rather than paste0 as the result would end up with \\ rather than \. In use > > cat('$$\\varphi=1+\\',rep('cfrac1{1+\\',n<-scan()),if(n)'d','dots',rep('}',n),'$$',sep='') 1: 3 2: Read 1 item$$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$ • +1 but instead of making it a function, if you have the user enter n as stdin on its first occurrence, you can save some characters: cat("$$\\varphi=1+\\",rep("cfrac1{1+\\",n<-scan()),if(n)"d","dots",rep("}",n),"$$",sep="") – plannapus Apr 8 '15 at 10:32 # JavaScript, 114109106 85 bytes thanks to George Reith f=n=>'$$\\varphi=1+\\'+((x='cfrac1{1+\\'.repeat(n))&&x+'d')+'dots'+'}'.repeat(n)+'$$'  This is my first entry in a codegolf contest! Please tell me how to improve. Previous entry (106 bytes): w="$$\\varphi=";y=n=>{return a=!n?w+"1+\\dots$$":w+"1+\\cfrac1{".repeat(n)+"1+\\ddots"+"}".repeat(n)+"$$"}  Previous entry (109 bytes): x="repeat",w="$$\\varphi=";y=n=>{return a=!n?w+"1+\\dots$$":w+"1+\\cfrac1{"[x](n)+"1+\\ddots"+"}"[x](n)+"$$"}  Previous entry (114 bytes): x="repeat";y=n=>{return a=!n?"$$\\varphi=1+\\dots$$":"$$\\varphi="+"1+\\cfrac1{"[x](n)+"1+\\ddots"+"}"[x](n)+"$$"}  Paste into browser console and call as f(n) where n is the number of 'steps'. Simplified code: function y(n) { if(n === 0) { return "$$\\varphi=1+\\dots$$"; } else { return "$$\\varphi=" + "1+\\cfrac1{".repeat(n) + "1+\\ddots"+"}".repeat(n)+"$$"; }  • x='repeat' makes it longer, not shorter: use .repeat as is and save 3 chars – edc65 Apr 8 '15 at 15:39 • @edc65 thanks!! – user31556 Apr 8 '15 at 22:43 • pastebin.com/uU7tgFm9 some more improvements – edc65 Apr 9 '15 at 6:17 • Can be made into 87 bytes like so: pastebin.com/0Hkv9uft – George Reith Apr 9 '15 at 12:37 • Or 85 bytes pastebin.com/k90Fyr2m – George Reith Apr 9 '15 at 13:41 # Pyth - 52 bytes The simple approach in Pyth, pretty much stolen from @Sp3000's Python solution. Uses string formatting operator %. %"$$\\varphi=1+\%sdots%s$$"(+*"cfrac1{1+\\"Q<\dQ*\}Q  % String formatting "$$ . . . $$" String to be formatted ( Tuple (no need to close it) + String concatenation *"..."Q String repetition input times <\dQ If Q>0 then d * String repetition \} The character "}" Q Q times  # Pyth, 50 bytes s["$$\\varphi=1+"*Q"\cfrac1{1+"\\<\dQ"dots"*Q\}"$$ • See my edit history :) – Optimizer Apr 8 '15 at 11:46 # JavaScript (ES6), 76 80 Partly recursive. The single/double d is most annoying part. F=n=>"$$\\varphi=1+\\"+(R=d=>n--?"cfrac1{1+\\"+R("d")+"}":d+"dots")("")+"$$"  Test In Firefox /FireBug console > for(i=0;i<5;i++)console.log(F(i))$$\varphi=1+\dots\varphi=1+\cfrac1{1+\ddots}\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}}$$ # Python, 90 116 since the most efficient solution has already been posted multiple times, i go with string replacement instead f=lambda n:'$$\\varphi=1+\ddots$$'if n==0 else f(n-1).replace('\ddots','\cfrac{1+\ddots}') # or, with exactly the same length x='\ddots';f=lambda n:'$$\\varphi=1+'x+'$$'if n==0 else f(n-1).replace(x,'\cfrac{1+'x+'}')  Edit: damn, overlooked the dots instead of ddots for n=0, now the recursive solution with an extra clause tacked on is too ugly to compete. x='$$\\varphi=1+\d%sots$$';f=lambda n:x%''if n==0 else x%'d'if n==1 else f(n-1).replace('\ddots','\cfrac{1+\ddots}')  • This is currently missing the n=0 special case (dots instead ddots). – randomra Apr 8 '15 at 15:08 # Haskell, 86 n%x=[1..n]>>x f n="$$\\varphi=1+"++n%"\\cfrac1{1+"++'\\':drop(0^n)"ddots"++n%"}"++"$\$"


Essentially the same approach as all solutions here. drop(0^n)"ddots" is cute, though!