Generate MathJax for the Golden Ratio Continued Fraction

17

2

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.

Calvin's Hobbies

Posted 2015-04-08T00:06:40.570

Reputation: 84 000

Just a note to those wanting to run the stack snippet: Like many (most?) stack snippets, this doesn't work in Safari. – Alex A. – 2015-04-08T00:53:26.597

The stack snippet doesn't work when you type stuff... it gives Uncaught ReferenceError: textbox is not defined – soktinpk – 2015-04-08T02:50:11.857

@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 – 2015-04-08T02:57:02.683

MathJax has been reenabled for PPCG! – wastl – 2018-07-10T13:53:10.977

Answers

6

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

Optimizer

Posted 2015-04-08T00:06:40.570

Reputation: 25 836

1A little shuffling gives 50: "$$\varphi=1+""\cfrac1{1+"ri:R*'\"ddots"R!>'}R*'$_ – Sp3000 – 2015-04-08T09:14:26.230

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 – 2015-04-08T11:49:00.250

@orlp and that is why I rolled back as there was no potential benefit in that solution being present here as well. – Optimizer – 2015-04-08T12:20:13.827

10

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)

Sp3000

Posted 2015-04-08T00:06:40.570

Reputation: 58 729

You beat me by 14 seconds! Also 70 chars. – xnor – 2015-04-08T01:21:00.683

2I think this works without using a double \ before cfrac. – xnor – 2015-04-08T01:29:58.987

@xnor Seems like it, thanks! And sorry for taking the Python golfs all the time... – Sp3000 – 2015-04-08T01:33:36.163

Nah, I've stolen my fair share of races to post from you. – xnor – 2015-04-08T01:34:18.893

4

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!

Alex A.

Posted 2015-04-08T00:06:40.570

Reputation: 23 761

"d"^(n>0) instead of (n>0?"d":"") would make it shorter. – plannapus – 2015-04-08T08:39:35.700

@plannapus: I don't understand what your name means but you're a genius! I had forgotten that "string"^0 was legit. – Alex A. – 2015-04-08T20:24:27.690

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 – 2015-04-09T06:07:04.253

I am waiting for a BF answer=) – flawr – 2015-04-09T09:06:38.090

@flawr: I hope you're not waiting on me for that... – Alex A. – 2015-04-10T04:27:51.693

4

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

Sp3000

Posted 2015-04-08T00:06:40.570

Reputation: 58 729

Two small improvements for 3 bytes (at the end of line 1 and line 3): http://pastebin.com/wEbKhuUH

– randomra – 2015-04-08T05:53:21.363

Hah the first and last line mirrors match up, didn't notice :P – Sp3000 – 2015-04-08T06:08:05.860

4

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

Martin Ender

Posted 2015-04-08T00:06:40.570

Reputation: 184 808

3

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}}}}}$$

MickyT

Posted 2015-04-08T00:06:40.570

Reputation: 11 735

3

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 $$

PhiNotPi

Posted 2015-04-08T00:06:40.570

Reputation: 26 739

+1 for using Element! It's time for Element to become a household name! – Alex A. – 2015-04-08T20:45:31.353

3

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}}}$$

vvye

Posted 2015-04-08T00:06:40.570

Reputation: 261

@Sp3000 The former doesn't, since Ruby apparently can't convert Booleans to integers. The latter worked though, so thanks for that! – vvye – 2015-04-08T14:00:12.393

2

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}}}$$

MickyT

Posted 2015-04-08T00:06:40.570

Reputation: 11 735

+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 – 2015-04-08T10:32:10.347

2

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.

randomra

Posted 2015-04-08T00:06:40.570

Reputation: 19 909

2

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)+"$$";
   }

user31556

Posted 2015-04-08T00:06:40.570

Reputation:

2x='repeat' makes it longer, not shorter: use .repeat as is and save 3 chars – edc65 – 2015-04-08T15:39:16.520

@edc65 thanks!! – None – 2015-04-08T22:43:23.053

http://pastebin.com/uU7tgFm9 some more improvements – edc65 – 2015-04-09T06:17:07.463

Can be made into 87 bytes like so: http://pastebin.com/0Hkv9uft

– George Reith – 2015-04-09T12:37:54.947

Or 85 bytes http://pastebin.com/k90Fyr2m

– George Reith – 2015-04-09T13:41:11.050

@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. – None – 2015-04-10T08:53:52.263

1

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

Maltysen

Posted 2015-04-08T00:06:40.570

Reputation: 25 023

1

Pyth, 50 bytes

s["$$\\varphi=1+"*Q"\cfrac1{1+"\\<\dQ"dots"*Q\}"$$

orlp

Posted 2015-04-08T00:06:40.570

Reputation: 37 067

1See my edit history :) – Optimizer – 2015-04-08T11:46:47.180

1

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}}}}$$

edc65

Posted 2015-04-08T00:06:40.570

Reputation: 31 086

0

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}')

DenDenDo

Posted 2015-04-08T00:06:40.570

Reputation: 2 811

This is currently missing the n=0 special case (dots instead ddots). – randomra – 2015-04-08T15:08:56.887

0

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!

Lynn

Posted 2015-04-08T00:06:40.570

Reputation: 55 648