17
\$\begingroup\$

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:

eq0

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:

    eq1

  • For n = 1, the output must be $$\varphi=1+\cfrac1{1+\ddots}$$.
    Which is rendered as:

    eq2

  • For n = 2, the output must be $$\varphi=1+\cfrac1{1+\cfrac1{1+\ddots}}$$.
    Which is rendered as:

    eq3

  • For n = 3, the output must be $$\varphi=1+\cfrac1{1+\cfrac1{1+\cfrac1{1+\ddots}}}$$.
    Which is rendered as:

    eq4

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.

\$\endgroup\$
4
  • \$\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.
    Commented Apr 8, 2015 at 0:53
  • \$\begingroup\$ The stack snippet doesn't work when you type stuff... it gives Uncaught ReferenceError: textbox is not defined \$\endgroup\$
    – soktinpk
    Commented Apr 8, 2015 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\$ Commented Apr 8, 2015 at 2:57
  • \$\begingroup\$ MathJax has been reenabled for PPCG! \$\endgroup\$
    – wastl
    Commented Jul 10, 2018 at 13:53

16 Answers 16

10
\$\begingroup\$

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

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ A little shuffling gives 50: "$$\varphi=1+""\cfrac1{1+"ri:R*'\"ddots"R!>'}R*'$_ \$\endgroup\$
    – Sp3000
    Commented Apr 8, 2015 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
    Commented Apr 8, 2015 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
    Commented Apr 8, 2015 at 12:20
4
\$\begingroup\$

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

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

Retina, 160 + 7 = 167 bytes

;`.+
$$$$\varphi=1+\dots#$0$$$$

;+(\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# ;#

;+`\\d?dots\d(\d*)
\cfrac1{1+\ddots$1}

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

\$\endgroup\$
4
\$\begingroup\$

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!

\$\endgroup\$
5
  • \$\begingroup\$ "d"^(n>0) instead of (n>0?"d":"") would make it shorter. \$\endgroup\$
    – plannapus
    Commented Apr 8, 2015 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.
    Commented Apr 8, 2015 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
    Commented Apr 9, 2015 at 6:07
  • \$\begingroup\$ I am waiting for a BF answer=) \$\endgroup\$
    – flawr
    Commented Apr 9, 2015 at 9:06
  • \$\begingroup\$ @flawr: I hope you're not waiting on me for that... \$\endgroup\$
    – Alex A.
    Commented Apr 10, 2015 at 4:27
3
\$\begingroup\$

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

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}}}}}$$
\$\endgroup\$
3
\$\begingroup\$

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.

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}}}$$
\$\endgroup\$
1
  • \$\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
    Commented Apr 8, 2015 at 14:00
2
\$\begingroup\$

J, 60 bytes

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

Usage:

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

   ((<;._2'$$\varphi=1+\ cfrac1{1+\ d dots } $$ ');@#~1,~5$1,],*) 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.

\$\endgroup\$
2
\$\begingroup\$

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}}}$$
\$\endgroup\$
1
  • \$\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
    Commented Apr 8, 2015 at 10:32
2
\$\begingroup\$

JavaScript, 114 109 106 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)+"$$";
   }
\$\endgroup\$
5
  • 2
    \$\begingroup\$ x='repeat' makes it longer, not shorter: use .repeat as is and save 3 chars \$\endgroup\$
    – edc65
    Commented Apr 8, 2015 at 15:39
  • \$\begingroup\$ pastebin.com/uU7tgFm9 some more improvements \$\endgroup\$
    – edc65
    Commented Apr 9, 2015 at 6:17
  • \$\begingroup\$ Can be made into 87 bytes like so: pastebin.com/0Hkv9uft \$\endgroup\$ Commented Apr 9, 2015 at 12:37
  • \$\begingroup\$ Or 85 bytes pastebin.com/k90Fyr2m \$\endgroup\$ Commented Apr 9, 2015 at 13:41
  • \$\begingroup\$ @edc65 I like it how you checked if n is equal to 0, by just n? : ... I didn't realise that if n = 0, n is false. \$\endgroup\$
    – user31556
    Commented Apr 10, 2015 at 8:53
1
\$\begingroup\$

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

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
\$\endgroup\$
1
\$\begingroup\$

Pyth, 50 bytes

s["$$\\varphi=1+"*Q"\cfrac1{1+"\\<\dQ"dots"*Q\}"$$
\$\endgroup\$
1
  • 1
    \$\begingroup\$ See my edit history :) \$\endgroup\$
    – Optimizer
    Commented Apr 8, 2015 at 11:46
1
\$\begingroup\$

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}}}}$$
\$\endgroup\$
0
\$\begingroup\$

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

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!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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