43
\$\begingroup\$

The Catalan numbers (OEIS) are a sequence of natural numbers often appearing in combinatorics.

The nth Catalan number is the number of Dyck words (balanced strings of parenthesis or brackets such as [[][]]; formally defined as a string using two characters a and b such that any substring starting from the beginning has number of a characters greater than or equal to number of b characters, and the entire string has the same number of a and b characters) with length 2n. The nth Catalan number (for \$n\ge0\$) is also explicitly defined as: $$C_n=\frac1{n+1}\binom{2n}n$$ Starting from \$n=0\$, the first 20 Catalan numbers are:

1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190...

Challenge

Write a full program or function that takes a non-negative integer n via STDIN or an acceptable alternative, and outputs the nth Catalan number. Your program must work at minimum for inputs 0-19.

I/O

Input

Your program must take input from STDIN, function arguments or any of the acceptable alternatives per this meta post. You can read the inputted number as its standard decimal represention, unary representation, or bytes.

  • If (and only if) your language cannot take input from STDIN or any acceptable alternative, it may take input from a hardcoded variable or suitable equivalent in the program.

Output

Your program must output the nth Catalan number to STDOUT, function result or any of the acceptable alternatives per this meta post. You can output the Catalan number in its standard decimal representation, unary representation or bytes.

The output should consist of the approriate Catalan number, optionally followed by one or more newlines. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation).


This is not about finding the language that is the shortest. This is about finding the shortest program in every language. Therefore, I will not accept an answer.

In this challenge, languages newer than the challenge are acceptable as long as they have an implementation. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8). Note also that built-ins for calculating the nth Catalan number are allowed.

Catalog

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 66127; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
6
  • \$\begingroup\$ Can we print/return a float rather than an integer? \$\endgroup\$
    – Alex A.
    Commented Dec 9, 2015 at 18:11
  • \$\begingroup\$ @AlexA. This is acceptable. \$\endgroup\$ Commented Dec 9, 2015 at 18:30
  • \$\begingroup\$ Shall there be a tag oeis? \$\endgroup\$
    – Vi.
    Commented Dec 9, 2015 at 21:36
  • 1
    \$\begingroup\$ @Vi. There was a meta discussion about that a while back and we agreed that oeis was unnecessary \$\endgroup\$ Commented Dec 9, 2015 at 21:37
  • \$\begingroup\$ @Vi. Here is the meta post: meta.codegolf.stackexchange.com/a/5546/8478. As for some reasoning, you can find OEIS-style challenges quite reliably with sequence and one of number or number-theory. Whether the given sequence actually is in OEIS, is completely irrelevant to the challenge. \$\endgroup\$ Commented Dec 10, 2015 at 7:57

57 Answers 57

28
\$\begingroup\$

C, 78 52 39 34 33 bytes

Even more C magic (thanks xsot):

c(n){return!n?:(4+6./~n)*c(n-1);}

?: is a GNU extension.


This time by expanding the recurrence below (thanks xnor and Thomas Kwa):

$$ \begin{equation} \begin{split} C_0 & = 1 \\ C_n & = \frac{2 (2n - 1)}{n + 1} C_{n - 1} \\ & = \frac{2 (2n+2-3)}{n+1} C_{n - 1} \\ & = 2 \left(2\frac{n+1}{n+1} - \frac{3}{n+1}\right) C_{n - 1} \\ & = \left(4 - \frac{6}{n+1}\right) C_{n - 1} \end{split} \end{equation} $$

c(n){return n?(4+6./~n)*c(n-1):1;}

-(n+1) is replaced by ~n, which is equivalent in two's complement and saves 4 bytes.


Again as a function, but this time exploiting the following recurrence:

$$ \begin{equation} \begin{split} C_0 & = 1 \\ C_n & = \frac{2 (2n - 1)}{n + 1} \cdot C_{n - 1} \end{split} \end{equation} $$

c(n){return n?2.*(2*n++-1)/n*c(n-2):1;}

c(n) enters an infinite recursion for negative n, although it's not relevant for this challenge.


Since calling a function seems an acceptable alternative to console I/O:

c(n){double c=1,k=2;while(k<=n)c*=1+n/k++;return c;}

c(n) takes an int and returns an int.


Original entry:

main(n){scanf("%d",&n);double c=1,k=2;while(k<=n)c*=1+n/k++;printf("%.0f",c);}

Instead of directly calculating the definition, the formula is rewritten as:

$$ \begin{equation} \begin{split} \frac{1}{n + 1} {2n \choose n} &= \frac{(2n)!}{(n!)^2 \cdot (n + 1)} \\ & = \frac{2n \cdot \ldots \cdot (n + 1)}{n! \cdot (n + 1)} \\ & = \frac{1}{n + 1} \cdot \frac{\prod_{k = 1}^n (n + k)}{\prod_{k = 1}^n k} \\ & = \frac{1}{n + 1} \cdot \prod_{k = 1}^n \frac{n + k}{k} \\ & = \frac{1}{n + 1} \cdot \prod_{k = 1}^n \left(1 + \frac{n}{k}\right) \\ & = \frac{1}{n + 1} (n + 1) \prod_{k = 2}^n \left(1 + \frac{n}{k}\right) \\ & = \prod_{k = 2}^n \left(1 + \frac{n}{k}\right) \end{split} \end{equation} $$

The formula assumes n >= 2, but the code accounts for n = 0 and n = 1 too.

In the C mess above, n and k have the same role as in the formula, while c accumulates the product. All calculations are performed in floating point using double, which is almost always a bad idea, but in this case the results are correct up to n = 19 at least, so it's ok.

float would have saved 1 byte, unfortunately it's not precise enough.

\$\endgroup\$
2
  • \$\begingroup\$ I can't test this now but I think you can shorten it further: c(n){return!n?:(4+6./~n)*c(n-1);} \$\endgroup\$
    – xsot
    Commented Dec 10, 2015 at 1:19
  • \$\begingroup\$ Thanks @xsot, I didn't know ?:! Apparently, it's a GNU C extension but I think it still qualifies. \$\endgroup\$ Commented Dec 10, 2015 at 10:27
25
\$\begingroup\$

Jelly, 4 bytes

Ḥc÷‘

Try it online!

How it works

Ḥc÷‘    Left argument: z

Ḥ       Compute 2z.
 c      Hook; apply combinations to 2z and z.
  ÷‘    Divide the result by z+1.
\$\endgroup\$
8
  • 1
    \$\begingroup\$ What does "hook' mean? How does c get 2z and z as its arguments? \$\endgroup\$
    – xnor
    Commented Dec 9, 2015 at 18:42
  • \$\begingroup\$ @xnor A hook means functions evaluated like f(x,g(x)). When there's a dyadic function followed by another dyadic function, the parser evaluates the first one as a hook. \$\endgroup\$
    – lirtosiast
    Commented Dec 9, 2015 at 18:46
  • 5
    \$\begingroup\$ @Dennis Is that really 4 bytes? With those non-ASCII characters, mothereff.in/byte-counter says 9 bytes \$\endgroup\$
    – Luis Mendo
    Commented Dec 9, 2015 at 20:12
  • \$\begingroup\$ @LuisMendo it's probably a different encoding \$\endgroup\$ Commented Dec 9, 2015 at 20:12
  • 5
    \$\begingroup\$ @LuisMendo Jelly uses its own, custom encoding default, where each character is a single byte. With UTF-8, the source code is indeed 9 bytes long. \$\endgroup\$
    – Dennis
    Commented Dec 9, 2015 at 20:16
11
\$\begingroup\$

TI-BASIC, 11 bytes

(2Ans) nCr Ans/(Ans+1

Strangely, nCr has higher precedence than multiplication.

\$\endgroup\$
11
\$\begingroup\$

CJam, 12 bytes

ri_2,*e!,\)/

Try it online.

Beyond input 11, you'll need to tell your Java VM to use more memory. And I wouldn't actually recommend going much beyond 11. In theory, it works for any N though, since CJam uses arbitrary-precision integers.

Explanation

CJam doesn't have a built-in for binomial coefficients, and computing them from three factorials takes a lot of bytes... so we'll have to do something better than that. :)

ri  e# Read input and convert it to integer N.
_   e# Duplicate.
2,  e# Push [0 1].
*   e# Repeat this N times, giving [0 1 0 1 ... 0 1] with N zeros and N ones.
e!  e# Compute the _distinct_ permutations of this array.
,   e# Get the number of permutations - the binomial. There happen to be 2n-over-n of
    e# of them. (Since 2n-over-n is the number of ways to choose n elements out of 2n, and
    e# and here we're choosing n positions in a 2n-element array to place the zeros in.)
\   e# Swap with N.
)/  e# Increment and divide the binomial coefficient by N+1.
\$\endgroup\$
2
  • \$\begingroup\$ This is really cool. +1 \$\endgroup\$ Commented Dec 9, 2015 at 18:31
  • \$\begingroup\$ This is clever. I tried it with calculating the factorials. It only takes two of the usual three since two of them are the same. It still used 17 bytes (ri_2*m!1$m!_*/\)/) in my implementation. The only good thing is that it's much faster. :) \$\endgroup\$ Commented Dec 10, 2015 at 6:05
11
\$\begingroup\$

Python 3, 33 bytes

f=lambda n:0**n or(4+6/~n)*f(n-1)

Uses the recurrence

f(0) = 1
f(n) = (4-6/(n+1)) * f(n-1)

The base case of 0 is handled as 0**n or, which stops as 1 when n==0 and otherwise evaluates the recursive expression on the right. The bitwise operator ~n==-n-1 shortens the denominator and saves on parens.

Python 3 is used for its float division. Python 2 could do the same with one more byte to write 6..

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Why not n<1 rather than 0**n ? \$\endgroup\$
    – feersum
    Commented Dec 9, 2015 at 18:12
  • \$\begingroup\$ @feersum It returns True for n==0 rather than 1. Of course, True == 1 but True is not 1 and it prints differently. I'd expect this to not be allowed. Do you know if we have a ruling on this? \$\endgroup\$
    – xnor
    Commented Dec 9, 2015 at 18:13
  • 1
    \$\begingroup\$ I believe that it is fine. isinstance(True, int) is True after all. \$\endgroup\$
    – feersum
    Commented Dec 9, 2015 at 18:17
  • 2
    \$\begingroup\$ I think it's still iffy in the general case and moreso here where the challenge specifies the output as a number or its representation. But, up to @quartata \$\endgroup\$
    – xnor
    Commented Dec 9, 2015 at 18:23
10
\$\begingroup\$

Mathematica, 16 13 bytes

CatalanNumber

Built-ins, amirite fellas :/

Non-builtin version (21 bytes):

Binomial[2#,#]/(#+1)&

A binomial-less version (25 bytes):

Product[(#+k)/k,{k,2,#}]&
\$\endgroup\$
7
\$\begingroup\$

J, 8 bytes

>:%~]!+:

This is a monadic train; it uses the (2x nCr x)/(x+1) formula. Try it here.

\$\endgroup\$
7
\$\begingroup\$

pl, 4 bytes

☼ç▲÷

Try it online.

Explanation

In pl, functions take their arguments off the stack and push the result back onto the stack. Normally when there are not enough arguments on the stack, the function simply fails silently. However, something special happens when the amount of arguments on the stack is one off from the arity of the function -- the input variable _ is added to the argument list:

☼ç▲÷

☼      double: takes _ as the argument since there is nothing on the stack
 ç     combinations: since there is only one item on the stack (and arity is 2), it adds _ to the argument list (combinations(2_,_))
  ▲    increment last used var (_)
   ÷   divide: adds _ to the argument list again

In effect, this is the pseudocode:

divide(combinations(double(_),_),_+1);
\$\endgroup\$
7
\$\begingroup\$

Sesos, 94 86 68 bytes

8 bytes by changing the factorial-er from version 1 to version 2.

18 bytes by computing n!(n+1)! in one step. Largely inspired by Dennis' primality test algorithm.

Hexdump:

0000000: 16f8de a59f17 a0ebba 7f4cd3 e05f3f cf0fd0 a0ebde  ..........L.._?......
0000015: b1c1bb 76fe18 8cc1bb 76fe1c e0fbda 390fda bde3d8  ...v.....v.....9.....
000002a: 000fbe af9d1b b47bc7 cfc11c b47bc7 cff1fa e07bda  .......{.....{.....{.
000003f: 39e83e cf07                                       9.>..

Try it online!

Uses the formula a(n) = (2n)! / (n!(n+1)!).

  • The factorial-er: version 1 (in-place, constant memory), version 2 (in-place, linear memory)
  • The multiplier: here (in place, constant memory)
  • The divider: here (does not halt if not divisible)

Assembler

set numin
set numout
get
jmp,sub 1,fwd 1,add 1,fwd 2,add 2,rwd 3,jnz
fwd 1,add 1
jmp
  jmp,sub 1,rwd 1,add 1,rwd 1,add 1,rwd 1,add 1,fwd 3,jnz
  rwd 1,sub 1,rwd 1,sub 1,rwd 1
  jmp,sub 1,fwd 3,add 1,rwd 3,jnz
  fwd 1
jnz
fwd 3
jmp
  jmp
    sub 1,rwd 1
    jmp,sub 1,rwd 1,add 1,rwd 1,add 1,fwd 2,jnz
    rwd 2
    jmp,sub 1,fwd 2,add 1,rwd 2,jnz
    fwd 3
  jnz
  rwd 1
  jmp,sub 1,jnz
  rwd 1
  jmp,sub 1,fwd 2,add 1,rwd 2,jnz
  fwd 3
jnz 
fwd 1
jmp
  jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
  fwd 1,sub 1,fwd 1
  jmp,sub 1,rwd 2,add 1,fwd 2,jnz
  rwd 1
jnz
rwd 2
jmp
  jmp
    sub 1,fwd 1
    jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
    fwd 2
    jmp,sub 1,rwd 2,add 1,fwd 2,jnz
    rwd 3
  jnz
  fwd 1
  jmp,sub 1,jnz
  fwd 1
  jmp,sub 1,rwd 2,add 1,fwd 2,jnz
  rwd 3
jnz 
fwd 1
jmp
  fwd 1,add 1,rwd 3
  jmp,sub 1,fwd 1,add 1,fwd 1,sub 1,rwd 2,jnz
  fwd 1
  jmp,sub 1,rwd 1,add 1,fwd 1,jnz
  fwd 1
jnz
fwd 1
put

Brainfuck equivalent

This Retina script is used to generate the brainfuck equivalent. Note that it only accepts one digit as command argument, and does not check if a command is in the comments.

[->+>>++<<<]>+
[[-<+<+<+>>>]<-<-<[->>>+<<<]>]>>>
[[-<[-<+<+>>]<<[->>+<<]>>>]<[-]<[->>+<<]>>>]>
[[->+>+<<]>->[-<<+>>]<]<<
[[->[->+>+<<]>>[-<<+>>]<<<]>[-]>[-<<+>>]<<<]>
[>+<<<[->+>-<<]>[-<+>]>]>
\$\endgroup\$
5
\$\begingroup\$

Pyth, 8

/.cyQQhQ

Try it online or run the Test Suite

Explanation

/.cyQQhQ   ## implicit: Q = eval(input())
/     hQ   ## integer division by (Q + 1)
 .c        ## nCr
   yQ      ## use Q * 2 as n
     Q     ## use Q as r
\$\endgroup\$
5
\$\begingroup\$

Julia, 23 bytes

n->binomial(2n,n)/(n+1)

This is an anonymous function that accepts an integer and returns a float. It uses the basic binomial formula. To call it, give it a name, e.g. f=n->....

\$\endgroup\$
5
\$\begingroup\$

Seriously, 9 bytes

,;;u)τ╣E\

Hex Dump:

2c3b3b7529e7b9455c

Try it online

Explanation:

,                   Read in evaluated input n
 ;;                 Duplicate it twice
   u)               Increment n and rotate it to bottom of stack
     τ╣             Double n, then push 2n-th row of Pascal's triangle
       E            Look-up nth element of the row, and so push 2nCn
        \           Divide it by the n+1 below it.
\$\endgroup\$
6
  • \$\begingroup\$ You can save a byte by exploiting the fact that the rows of Pascal's triangle are symmetric, so the median of the 2nth row is C(2n,n). Thus: ,;u@τ╣║/ for 8 bytes. \$\endgroup\$
    – user45941
    Commented Dec 17, 2015 at 3:02
  • \$\begingroup\$ What? Isn't 2nCn the max of the 2nth row? \$\endgroup\$
    – quintopia
    Commented Dec 17, 2015 at 17:04
  • \$\begingroup\$ Yes, and it's also the median. So, both and M would work. \$\endgroup\$
    – user45941
    Commented Dec 17, 2015 at 22:02
  • \$\begingroup\$ @Mego I worry about your implementation of median if something can be both the median and max in the case that the list isn't all the same number. If you mean "in the middle of the list" then you might choose a different name for it... \$\endgroup\$
    – quintopia
    Commented Dec 19, 2015 at 11:16
  • \$\begingroup\$ Yes, it's the middle of the list. For sorted lists, it's the typical statistical median, but for unsorted lists it's just the middle (or average of 2 middle elements) \$\endgroup\$
    – user45941
    Commented Dec 19, 2015 at 14:19
4
\$\begingroup\$

JavaScript (ES6), 24 bytes

Based on the Python answer.

c=x=>x?(4+6/~x)*c(x-1):1

How it works

c=x=>x?(4+6/~x)*c(x-1):1
c=x=>                     // Define a function c that takes a parameter x and returns:
     x?               :1  //  If x == 0, 1.
       (4+6/~x)           //  Otherwise, (4 + (6 / (-x - 1)))
               *c(x-1)    //  times the previous item in the sequence.

I think this is the shortest it can get, but suggestions are welcome!

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

Matlab, 35 25 bytes

@(n)nchoosek(2*n,n)/(n+1)

Octave, 23 bytes

@(n)nchoosek(2*n,n++)/n
\$\endgroup\$
5
  • 2
    \$\begingroup\$ You can use @(n) instead of function, anonymous functions are ok. \$\endgroup\$ Commented Dec 9, 2015 at 17:47
  • \$\begingroup\$ I've seen several answers on here before that had workspace variables being accessed (implying they had already been set by the user elsewhere). Scripts in MATLAB/Octave also can appear as simple snippets. I've re-made it into a function for now... \$\endgroup\$
    – costrom
    Commented Dec 9, 2015 at 17:47
  • 1
    \$\begingroup\$ You can knock off 2 more bytes by post-incrementing n: @(n)nchoosek(2*n,n++)/n \$\endgroup\$
    – beaker
    Commented Dec 9, 2015 at 21:55
  • \$\begingroup\$ @beaker thanks for the tip! it only works in Octave though, not Matlab, so I've split it apart \$\endgroup\$
    – costrom
    Commented Dec 9, 2015 at 22:09
  • \$\begingroup\$ @costrom That's interesting. I guess .../++n doesn't work either. :/ \$\endgroup\$
    – beaker
    Commented Dec 9, 2015 at 23:19
4
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 3 chars / 6 bytes

Мƅï

Try it here (Firefox only).

Builtins ftw! So glad I implemented math.js early on.

Bonus solution, 12 chars / 19 bytes

Мơ 2*ï,ï)/⧺ï

Try it here (Firefox only).

Ay! 19th byte!

Evaluates to pseudo-ES6 as:

nchoosek(2*input,input)/(input+1)
\$\endgroup\$
0
3
\$\begingroup\$

Haskell, 27 bytes

g 0=1
g n=(4-6/(n+1))*g(n-1)

A recursive formula. There's got to be a way to save on parens...

Directly taking the product was 2 bytes longer:

g n=product[4-6/i|i<-[2..n+1]]
\$\endgroup\$
3
  • \$\begingroup\$ Where does your code read from stdin or write to stdout? \$\endgroup\$ Commented Dec 9, 2015 at 18:23
  • 2
    \$\begingroup\$ @user2845840 Functions are one of the acceptable alternatives linked to in the spec. \$\endgroup\$
    – xnor
    Commented Dec 9, 2015 at 18:25
  • \$\begingroup\$ g(n-1) => g$n-1 saves one byte. Edit: actually this doesn't work because then the formula is interpreted as (...*g) (n-1). \$\endgroup\$ Commented Dec 13, 2015 at 1:41
3
\$\begingroup\$

Dyalog APL, 9 bytes

+∘1÷⍨⊢!+⍨

This is a monadic train; it uses the (2x nCr x)/(x+1) formula. Try it online here.

\$\endgroup\$
3
\$\begingroup\$

C, 122 121 119 108 bytes

main(j,v)char**v;{long long p=1,i,n=atoi(v[1]);for(j=0,i=n+1;i<2*n;p=(p*++i)/++j);p=n?p/n:p;printf("%d",p);}

I used gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) to compile in a windows cygwin environment. Input comes in on the command line. It's similar to Sherlock9's Python solution but the loops are combined into one to avoid overflow and get output up to the 20th Catalan number (n=19).

\$\endgroup\$
5
  • 1
    \$\begingroup\$ You can remove the space after the comma in the main definition to save a byte. \$\endgroup\$
    – Alex A.
    Commented Dec 9, 2015 at 19:25
  • \$\begingroup\$ Nice, I'll edit the post now \$\endgroup\$
    – cleblanc
    Commented Dec 9, 2015 at 20:24
  • \$\begingroup\$ You can save 2 more bytes with char**v rather than char *v[]. (The space before * is not needed, and the types are equivalent.) \$\endgroup\$
    – Mat
    Commented Dec 9, 2015 at 21:02
  • \$\begingroup\$ Sure enough, that works great. Thanks Mat \$\endgroup\$
    – cleblanc
    Commented Dec 9, 2015 at 21:10
  • \$\begingroup\$ This uses some stuff from the tips page to shorten it. Note though that for Ideone I hardcoded a value for n. \$\endgroup\$ Commented Dec 9, 2015 at 21:53
3
\$\begingroup\$

Javagony, 223 bytes

public class C{public static int f(int a,int b){try{int z=1/(b-a);}catch(Exception e){return 1;}return a*f(a+1,b);}public static void main(String[]s){int m=Integer.parseInt(s[0])+1;System.out.println(f(m,2*m-1)/f(1,m)/m);}}

Fully expanded:

public class C {
    public static int f(int a,int b){
        try {
            int z=1/(b-a);
        } catch (Exception e){
            return 1;
        }
        return a*f(a+1,b);
    }
    public static void main(String[] s){
        int m=Integer.parseInt(s[0])+1;
        System.out.println(f(m,2*m-1)/f(1,m)/m);
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ Esolangs entry doesn't matter - as long as you use an interpreter made before the contest, it's all good and valid. \$\endgroup\$ Commented Dec 28, 2015 at 14:52
  • \$\begingroup\$ Ain't gonna win anyway^^ \$\endgroup\$
    – flawr
    Commented Dec 28, 2015 at 15:09
  • \$\begingroup\$ It is java, so yeah. \$\endgroup\$
    – Riker
    Commented Dec 28, 2015 at 15:23
  • 1
    \$\begingroup\$ @Riker Well, it's worse than Java. \$\endgroup\$
    – Jakob
    Commented Aug 20, 2017 at 17:21
3
\$\begingroup\$

R, 35 28 16 bytes

numbers::catalan

Edit: Use numbers package builtin.

\$\endgroup\$
3
\$\begingroup\$

05AB1E, 6 bytes

Dxcr>/

Explanation:

Code:     Stack:               Explanation:

Dxcr>/

D         [n, n]               # Duplicate of the stack. Since it's empty, input is used.
 x        [n, n, 2n]           # Pops a, pushes a, a * 2
  c       [n, n nCr 2n]        # Pops a,b pushes a nCr b
   r      [n nCr 2n, n]        # Reverses the stack
    >     [n nCr 2n, n + 1]    # Increment on the last item
     /    [(n nCr 2n)/(n + 1)] # Divides the last two items
                               # Implicit, nothing has printed, so we print the last item
\$\endgroup\$
3
\$\begingroup\$

R, 28 bytes

Not using a package, so slightly longer than a previous answer

choose(2*(n=scan()),n)/(n+1)
\$\endgroup\$
3
\$\begingroup\$

Oasis, 9 bytes

nxx«*n>÷1

Try it online!

Oasis is a language designed by Adnan which is specialized in sequences.

Here, we shall use the following relationship kindly provided by Stefano Sanfilippo:

Currently, this language can do recursion and closed form.

To specify that a(0)=1 is simple: just add the 1 at the end.

For example, if a sequence begins with a(0)=0 and a(1)=1, just put 10 at the end.

Unfortunately, all sequences must be 0-indexed.

nxx«*n>÷1                        stack
        1  a(0)=1

n          push n (input)        n
 x         double                2n
  x        double                4n
   «       minus 2               4n-2
    *      multiply: second      (4n-2)*a(n-1)
           argument is missing,
           so a(n-1) is used.
     n     push n (input)        (4n-2)*a(n-1) n
      >    add 1                 (4n-2)*a(n-1) n+1
       ÷   integer division      (4n-2)*a(n-1)/(n+1)
                               = ((4n-2)/(n+1))*a(n-1)
                               = ((4n+4-6)/(n+1))*a(n-1)
                               = ((4n+4)/(n+1) - 6/(n+1))*a(n-1)
                               = (4-6/(n+1))*a(n-1)

Closed-form:

10 bytes

nx!n!n>!*÷

Try it online!

nx!n!n>!*÷

n           push n (input)
 x          double
  !         factorial: stack is now [(2n)!]
   n        push n (input)
    !       factorial: stack is now [(2n)! n!]
     n      push n (input)
      >     add 1
       !    factorial: stack is now [(2n)! n! (n+1)!]
        *   multiply: stack is now [(2n)! (n!(n+1)!)]
         ÷  divide: stack is now [(2n)!/(n!(n+1)!)]
\$\endgroup\$
3
\$\begingroup\$

TeX, 231 bytes

\newcommand{\f}[1]{\begingroup\count0=1\count1=2\count2=2\count3=0\loop\multiply\count0 by\the\count1\divide\count0 by\the\count2\advance\count1 by4\advance\count2 by1\advance\count3 by1
\ifnum\count3<#1\repeat\the\count0\endgroup}

Usage

\documentclass[12pt,a4paper]{article}
\begin{document}
\newcommand{\f}[1]{\begingroup\count0=1\count1=2\count2=2\count3=0\loop\multiply\count0 by\the\count1\divide\count0 by\the\count2\advance\count1 by4\advance\count2 by1\advance\count3 by1
\ifnum\count3<#1\repeat\the\count0\endgroup}

\newcount \i
\i = 0
\loop
\f{\the\i}
\advance \i by 1
\ifnum \i < 15 \repeat
\end{document}

enter image description here

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

Japt, 16 bytes

Even Mathematica is shorter. :-/

U*2ª1 o àU l /°U

Try it online!

Ungolfed and explanation

U*2ª 1 o àU l /° U
U*2||1 o àU l /++U

         // Implicit: U = input number
U*2||1   // Take U*2. If it is zero, take 1.
o àU     // Generate a range of this length, and calculate all combinations of length U.
l /++U   // Take the length of the result and divide by (U+1).
         // Implicit: output result

Alternate version, based on the recursive formula:

C=_?(4+6/~Z *C$(Z-1):1};$C(U
\$\endgroup\$
2
\$\begingroup\$

Vitsy, 13 Bytes

VV2*FVF/V1+F/
V              Capture the input as a final global variable.
 V             Push it back.
  2*           Multiply it by 2
    F          Factorial.
     VF        Factorial of the input.
       /       Divide the second to top by the first.
        V1+    1+input
           F   Factorial.
            /  Divide.

This is a function in Vitsy. How to make it a program that does this, you ask? Concatenate N. c:

Try it online!

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

Milky Way 1.5.14, 14 bytes

':2K;*Ny;1+/A!

Explanation

'               # read input from the command line
 :              # duplicate the TOS
  2      1      # push integer to the stack
   K            # push a Pythonic range(0, TOS) as a list
    ;   ;       # swap the TOS and the STOS
     *          # multiply the TOS and STOS
      N         # push a list of the permutations of the TOS (for lists)
       y        # push the length of the TOS
          +     # add the STOS to the TOS
           /    # divide the TOS by the STOS
            A   # push the integer representation of the TOS
             !  # output the TOS

or, alternatively, the much more efficient version:


Milky Way 1.5.14, 22 bytes

'1%{;K£1+k1-6;/4+*}A!

Explanation

'                      # read input from the command line
 1     1  1 6  4       # push integer to the stack
  %{  £           }    # for loop
    ;        ;         # swap the TOS and the STOS
     K                 # push a Pythonic range(0, TOS) as a list
        +       +      # add the TOS and STOS
         k             # push the negative absolute value of the TOS
           -           # subtract the STOS from the TOS
              /        # divide the TOS by the STOS
                 *     # multiply the TOS and the STOS
                   A   # push the integer representation of the TOS
                    !  # output the TOS

Usage

python3 milkyway.py <path-to-code> -i <input-integer>
\$\endgroup\$
2
\$\begingroup\$

Clojure/ClojureScript, 53 bytes

(defn c[x](if(= 0 x)1(*(c(dec x))(- 4(/ 6(inc x))))))

Clojure can be pretty frustrating to golf in. It's very pithy while still being very readable, but some of the niftier features are really verbose. (inc x) is more idiomatic than (+ x 1) and "feels" more concise, but doesn't actually save characters. And writing chains of operations is nicer as (->> x inc (/ 6) (- 4)), but it's actually longer than just doing it the ugly way.

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

Ruby, 30 bytes

c=->n{n<1?1:c[n-1]*(4+6.0/~n)}

Thanks to xsot, saved few bytes by using complement.

Ungolfed:

c = -> n {
  n < 1 ? 1 : c[n-1]*(4+6.0/~n)
}

Usage:

> c=->n{n<1?1:c[n-1]*(4+6.0/~n)}
> c[10]
=> 16796.0
\$\endgroup\$
2
\$\begingroup\$

Prolog, 42 bytes

Using recursion is almost always the way to go with Prolog.

Code:

0*1.
N*X:-M is N-1,M*Y,X is(4-6/(N+1))*Y.

Example:

19*X.
X = 1767263190.0

Try it online here

\$\endgroup\$
4
  • \$\begingroup\$ Are you redefining the * symbol here? \$\endgroup\$ Commented Dec 12, 2015 at 17:15
  • \$\begingroup\$ @PaŭloEbermann not exactly. I'm defining a new dyadic predicate called *. I can still use the regular arithmetic one. In the program above M*Y is my defined predicate while (4-6/(N+1))*Y is regular multiplication. \$\endgroup\$
    – Emigna
    Commented Dec 12, 2015 at 17:27
  • \$\begingroup\$ It's slightly shorter than writing it as p(X,Y):- which is nice for code golf. \$\endgroup\$
    – Emigna
    Commented Dec 12, 2015 at 17:29
  • \$\begingroup\$ -6/(N+1) can be +6/ \N. Also, your link seems to direct to someone else's code now \$\endgroup\$
    – Jo King
    Commented Feb 2, 2022 at 4:55

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.