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


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.


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.


  • \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).


The smallest submission in bytes wins. Tiebreaker goes to the earlier submission.

  • \$\begingroup\$ Just a note to those wanting to run the stack snippet: Like many (most?) stack snippets, this doesn't work in Safari. \$\endgroup\$ – Alex A. Apr 8 '15 at 0:53
  • \$\begingroup\$ The stack snippet doesn't work when you type stuff... it gives Uncaught ReferenceError: textbox is not defined \$\endgroup\$ – soktinpk Apr 8 '15 at 2:50
  • \$\begingroup\$ @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. \$\endgroup\$ – Calvin's Hobbies Apr 8 '15 at 2:57
  • \$\begingroup\$ MathJax has been reenabled for PPCG! \$\endgroup\$ – wastl Jul 10 '18 at 13:53

16 Answers 16


CJam, 51 50 bytes


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


N = 4


N = 15


UPDATE - 1 byte saved thanks to Sp3000!

Try it online here

|improve this answer|||||
  • 1
    \$\begingroup\$ A little shuffling gives 50: "$$\varphi=1+""\cfrac1{1+"ri:R*'\"ddots"R!>'}R*'$_ \$\endgroup\$ – Sp3000 Apr 8 '15 at 9:14
  • \$\begingroup\$ 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. \$\endgroup\$ – orlp Apr 8 '15 at 11:49
  • \$\begingroup\$ @orlp and that is why I rolled back as there was no potential benefit in that solution being present here as well. \$\endgroup\$ – Optimizer Apr 8 '15 at 12:20

Python, 70 68 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)
|improve this answer|||||
  • \$\begingroup\$ You beat me by 14 seconds! Also 70 chars. \$\endgroup\$ – xnor Apr 8 '15 at 1:21
  • 2
    \$\begingroup\$ I think this works without using a double \ before cfrac. \$\endgroup\$ – xnor Apr 8 '15 at 1:29
  • \$\begingroup\$ @xnor Seems like it, thanks! And sorry for taking the Python golfs all the time... \$\endgroup\$ – Sp3000 Apr 8 '15 at 1:33
  • \$\begingroup\$ Nah, I've stolen my fair share of races to post from you. \$\endgroup\$ – xnor Apr 8 '15 at 1:34

><>, 89 86 + 3 = 89 bytes


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)

|improve this answer|||||
  • \$\begingroup\$ Two small improvements for 3 bytes (at the end of line 1 and line 3): pastebin.com/wEbKhuUH \$\endgroup\$ – randomra Apr 8 '15 at 5:53
  • \$\begingroup\$ Hah the first and last line mirrors match up, didn't notice :P \$\endgroup\$ – Sp3000 Apr 8 '15 at 6:08

Retina, 160 + 7 = 167 bytes


;+(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0) $1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10# ;#


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).

|improve this answer|||||

Julia, 76 73 bytes


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 ^.


julia> f(0)

julia> f(4)

Suggestions are welcome as always!

Edit: Saved 3 bytes thanks to plannapus!

|improve this answer|||||
  • \$\begingroup\$ "d"^(n>0) instead of (n>0?"d":"") would make it shorter. \$\endgroup\$ – plannapus Apr 8 '15 at 8:39
  • \$\begingroup\$ @plannapus: I don't understand what your name means but you're a genius! I had forgotten that "string"^0 was legit. \$\endgroup\$ – Alex A. Apr 8 '15 at 20:24
  • \$\begingroup\$ you're welcome. My pseudonym is the name of a radiolarian genus, being myself a radiolarian paleontologist. It translates to "flattened turnip" i think :) \$\endgroup\$ – plannapus Apr 9 '15 at 6:07
  • \$\begingroup\$ I am waiting for a BF answer=) \$\endgroup\$ – flawr Apr 9 '15 at 9:06
  • \$\begingroup\$ @flawr: I hope you're not waiting on me for that... \$\endgroup\$ – Alex A. Apr 10 '15 at 4:27

Element, 63 Chars


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 $$
|improve this answer|||||
  • \$\begingroup\$ +1 for using Element! It's time for Element to become a household name! \$\endgroup\$ – Alex A. Apr 8 '15 at 20:45

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



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:

FROM (SELECT N FROM(VALUES(0),(1),(2),(3),(4),(5))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}}}}}$$
|improve this answer|||||

Ruby, 76 75 71 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.


To be applied like so:


|improve this answer|||||
  • \$\begingroup\$ @Sp3000 The former doesn't, since Ruby apparently can't convert Booleans to integers. The latter worked though, so thanks for that! \$\endgroup\$ – vvye Apr 8 '15 at 14:00

J, 60 bytes

(<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*


   ((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*) 0

   ((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*) 3


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 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
Read 1 item
|improve this answer|||||
  • \$\begingroup\$ +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="") \$\endgroup\$ – plannapus Apr 8 '15 at 10:32

JavaScript, 114 109 106 85 bytes thanks to George Reith


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)+"$$";
|improve this answer|||||
  • 2
    \$\begingroup\$ x='repeat' makes it longer, not shorter: use .repeat as is and save 3 chars \$\endgroup\$ – edc65 Apr 8 '15 at 15:39
  • \$\begingroup\$ @edc65 thanks!! \$\endgroup\$ – user31556 Apr 8 '15 at 22:43
  • \$\begingroup\$ pastebin.com/uU7tgFm9 some more improvements \$\endgroup\$ – edc65 Apr 9 '15 at 6:17
  • \$\begingroup\$ Can be made into 87 bytes like so: pastebin.com/0Hkv9uft \$\endgroup\$ – George Reith Apr 9 '15 at 12:37
  • \$\begingroup\$ Or 85 bytes pastebin.com/k90Fyr2m \$\endgroup\$ – 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 %.


Try it online here.

%                  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
|improve this answer|||||

Pyth, 50 bytes

|improve this answer|||||
  • 1
    \$\begingroup\$ See my edit history :) \$\endgroup\$ – Optimizer Apr 8 '15 at 11:46

JavaScript (ES6), 76 80

Partly recursive. The single/double d is most annoying part.


Test In Firefox /FireBug console

> for(i=0;i<5;i++)console.log(F(i))

|improve this answer|||||

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}')
|improve this answer|||||
  • \$\begingroup\$ This is currently missing the n=0 special case (dots instead ddots). \$\endgroup\$ – randomra Apr 8 '15 at 15:08

Haskell, 86

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!

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.