Catalan Numbers

36

3

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 >= 0) is also explicitly defined as:

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>

a spaghetto

Posted 2015-12-09T17:39:41.920

Reputation: 10 647

Can we print/return a float rather than an integer? – Alex A. – 2015-12-09T18:11:06.387

@AlexA. This is acceptable. – a spaghetto – 2015-12-09T18:30:59.527

Shall there be a tag [tag:OEIS]? – Vi. – 2015-12-09T21:36:50.100

1@Vi. There was a meta discussion about that a while back and we agreed that [tag:oeis] was unnecessary – a spaghetto – 2015-12-09T21:37:40.013

@Vi. Here is the meta post: http://meta.codegolf.stackexchange.com/a/5546/8478. As for some reasoning, you can find OEIS-style challenges quite reliably with [tag:sequence] and one of [tag:number] or [tag:number-theory]. Whether the given sequence actually is in OEIS, is completely irrelevant to the challenge.

– Martin Ender – 2015-12-10T07:57:19.430

@MartinBüttner, Thinking about making a challenge about generating some sequence not in OEIS, but can't think up any viable formulation barring just pseudorandom numbers.. – Vi. – 2015-12-10T15:22:28.460

Answers

26

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

yet another recursion

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:

recur

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:

rewrite

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.

Stefano Sanfilippo

Posted 2015-12-09T17:39:41.920

Reputation: 1 059

I can't test this now but I think you can shorten it further: c(n){return!n?:(4+6./~n)*c(n-1);} – xsot – 2015-12-10T01:19:29.470

Thanks @xsot, I didn't know ?:! Apparently, it's a GNU C extension but I think it still qualifies. – Stefano Sanfilippo – 2015-12-10T10:27:35.823

23

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.

Dennis

Posted 2015-12-09T17:39:41.920

Reputation: 196 637

1What does "hook' mean? How does c get 2z and z as its arguments? – xnor – 2015-12-09T18:42:05.097

@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. – lirtosiast – 2015-12-09T18:46:16.753

5

@Dennis Is that really 4 bytes? With those non-ASCII characters, https://mothereff.in/byte-counter says 9 bytes

– Luis Mendo – 2015-12-09T20:12:24.407

@LuisMendo it's probably a different encoding – undergroundmonorail – 2015-12-09T20:12:50.933

3@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. – Dennis – 2015-12-09T20:16:39.297

@Dennis Sorry about my confusion then – Luis Mendo – 2015-12-09T20:25:33.913

Is there any info on this language available? – Adám – 2015-12-09T22:37:54.963

@NBZ At the moment, only this and the conversations here.

– Dennis – 2015-12-09T22:47:31.843

11

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,#}]&

a spaghetto

Posted 2015-12-09T17:39:41.920

Reputation: 10 647

11

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.

Martin Ender

Posted 2015-12-09T17:39:41.920

Reputation: 184 808

This is really cool. +1 – a spaghetto – 2015-12-09T18:31:29.770

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. :) – Reto Koradi – 2015-12-10T06:05:52.093

10

TI-BASIC, 11 bytes

(2Ans) nCr Ans/(Ans+1

Strangely, nCr has higher precedence than multiplication.

lirtosiast

Posted 2015-12-09T17:39:41.920

Reputation: 20 331

10

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

xnor

Posted 2015-12-09T17:39:41.920

Reputation: 115 687

Why not n<1 rather than 0**n ? – feersum – 2015-12-09T18:12:15.613

@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? – xnor – 2015-12-09T18:13:56.210

I believe that it is fine. isinstance(True, int) is True after all. – feersum – 2015-12-09T18:17:01.507

2I 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 – xnor – 2015-12-09T18:23:59.853

7

J, 8 bytes

>:%~]!+:

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

lirtosiast

Posted 2015-12-09T17:39:41.920

Reputation: 20 331

7

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

a spaghetto

Posted 2015-12-09T17:39:41.920

Reputation: 10 647

6

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.

[->+>>++<<<]>+
[[-<+<+<+>>>]<-<-<[->>>+<<<]>]>>>
[[-<[-<+<+>>]<<[->>+<<]>>>]<[-]<[->>+<<]>>>]>
[[->+>+<<]>->[-<<+>>]<]<<
[[->[->+>+<<]>>[-<<+>>]<<<]>[-]>[-<<+>>]<<<]>
[>+<<<[->+>-<<]>[-<+>]>]>

Leaky Nun

Posted 2015-12-09T17:39:41.920

Reputation: 45 011

5

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

FryAmTheEggman

Posted 2015-12-09T17:39:41.920

Reputation: 16 206

5

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.

quintopia

Posted 2015-12-09T17:39:41.920

Reputation: 3 899

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. – Mego – 2015-12-17T03:02:03.883

What? Isn't 2nCn the max of the 2nth row? – quintopia – 2015-12-17T17:04:26.963

Yes, and it's also the median. So, both and M would work. – Mego – 2015-12-17T22:02:23.503

@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... – quintopia – 2015-12-19T11:16:32.137

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) – Mego – 2015-12-19T14:19:58.103

I would not have guessed that from the name. – quintopia – 2015-12-19T14:56:45.877

4

Matlab, 35 25 bytes

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

Octave, 23 bytes

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

costrom

Posted 2015-12-09T17:39:41.920

Reputation: 478

2You can use @(n) instead of function, anonymous functions are ok. – FryAmTheEggman – 2015-12-09T17:47:28.673

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... – costrom – 2015-12-09T17:47:48.950

1You can knock off 2 more bytes by post-incrementing n: @(n)nchoosek(2*n,n++)/n – beaker – 2015-12-09T21:55:41.913

@beaker thanks for the tip! it only works in Octave though, not Matlab, so I've split it apart – costrom – 2015-12-09T22:09:20.410

@costrom That's interesting. I guess .../++n doesn't work either. :/ – beaker – 2015-12-09T23:19:49.143

4

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

Alex A.

Posted 2015-12-09T17:39:41.920

Reputation: 23 761

4

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!

ETHproductions

Posted 2015-12-09T17:39:41.920

Reputation: 47 880

4

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

Mama Fun Roll

Posted 2015-12-09T17:39:41.920

Reputation: 7 234

3

Dyalog APL, 9 bytes

+∘1÷⍨⊢!+⍨

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

lirtosiast

Posted 2015-12-09T17:39:41.920

Reputation: 20 331

3

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

xnor

Posted 2015-12-09T17:39:41.920

Reputation: 115 687

Where does your code read from stdin or write to stdout? – user2845840 – 2015-12-09T18:23:53.443

2

@user2845840 Functions are one of the acceptable alternatives linked to in the spec.

– xnor – 2015-12-09T18:25:24.943

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). – Reinstate Monica – 2015-12-13T01:41:21.520

3

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

cleblanc

Posted 2015-12-09T17:39:41.920

Reputation: 3 360

1You can remove the space after the comma in the main definition to save a byte. – Alex A. – 2015-12-09T19:25:56.123

Nice, I'll edit the post now – cleblanc – 2015-12-09T20:24:32.690

You can save 2 more bytes with char**v rather than char *v[]. (The space before * is not needed, and the types are equivalent.) – Mat – 2015-12-09T21:02:31.093

Sure enough, that works great. Thanks Mat – cleblanc – 2015-12-09T21:10:26.253

This uses some stuff from the tips page to shorten it. Note though that for Ideone I hardcoded a value for n. – FryAmTheEggman – 2015-12-09T21:53:59.010

3

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

flawr

Posted 2015-12-09T17:39:41.920

Reputation: 40 560

Esolangs entry doesn't matter - as long as you use an interpreter made before the contest, it's all good and valid. – Addison Crump – 2015-12-28T14:52:40.717

Ain't gonna win anyway^^ – flawr – 2015-12-28T15:09:37.413

It is java, so yeah. – Rɪᴋᴇʀ – 2015-12-28T15:23:54.730

1@Riker Well, it's worse than Java. – Jakob – 2017-08-20T17:21:53.360

2

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

ETHproductions

Posted 2015-12-09T17:39:41.920

Reputation: 47 880

2

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!

Addison Crump

Posted 2015-12-09T17:39:41.920

Reputation: 10 763

2

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>

Zach Gates

Posted 2015-12-09T17:39:41.920

Reputation: 6 152

2

Octave, 22 bytes

@(n)prod(4-6./(2:n+1))

alephalpha

Posted 2015-12-09T17:39:41.920

Reputation: 23 988

2

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.

MattPutnam

Posted 2015-12-09T17:39:41.920

Reputation: 521

2

R, 35 28 16 bytes

numbers::catalan

Edit: Use numbers package builtin.

mnel

Posted 2015-12-09T17:39:41.920

Reputation: 826

2

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

Emigna

Posted 2015-12-09T17:39:41.920

Reputation: 50 798

Are you redefining the * symbol here? – Paŭlo Ebermann – 2015-12-12T17:15:10.210

@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. – Emigna – 2015-12-12T17:27:29.103

It's slightly shorter than writing it as p(X,Y):- which is nice for code golf. – Emigna – 2015-12-12T17:29:44.837

2

Ceylon, 60 bytes

Integer c(Integer n)=>(1:n).fold(1)((p,i)=>p*(n+i)/i)/(n+1);

This works up to C30, as Ceylon's Integers are signed 64-bit numbers (C31 has overflow, will be calculated as -4050872099593203).

I don't know if Ceylon has any built-in higher mathematical functions, but then importing the right package would probably longer than just calculating this by foot.

// Catalan number C_n
//
// Question:  http://codegolf.stackexchange.com/q/66127/2338
// My answer: http://codegolf.stackexchange.com/a/66425/2338

Integer c(Integer n) =>
        // sequence of length n, starting at 1.
        (1:n)
        // starting with 1, for each element i, multiply the result
        // of the previous step by (n+i) and then divide it by i.
    .fold(1)((p, i) => p * (n + i) / i)
        // divide the result by n+1.
        / (n + 1);

Paŭlo Ebermann

Posted 2015-12-09T17:39:41.920

Reputation: 1 010

2

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

Adnan

Posted 2015-12-09T17:39:41.920

Reputation: 41 965

2

MATL, 8 bytes

2*GXnGQ/

Try it online!

Explanation

2*     % take number n as input and multiply by 2
G      % push input again
Xn     % compute "2*n choose n"
G      % push input again
Q      % add 1
/      % divide

Luis Mendo

Posted 2015-12-09T17:39:41.920

Reputation: 87 464

2

R, 28 bytes

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

choose(2*(n=scan()),n)/(n+1)

Frédéric

Posted 2015-12-09T17:39:41.920

Reputation: 2 059

2

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)!)]

Leaky Nun

Posted 2015-12-09T17:39:41.920

Reputation: 45 011

1

Alice, 16 bytes

/o
\i@/..2*~C~h:

Try it online!

Explanation

This is a basic framework for arithmetic programs to read and write integer I/O and process them in Cardinal mode:

/o
\i@/...

As for the actual computation, I'm using the usual formula given in the challenge:

..   Make two copies of the input.
2*   Double one copy.
~    Swap it with another copy.
C    Compute the binomial coefficient (2n,n).
~    Swap with the third copy.
h    Increment.
:    Divide to compute C_n = (2n,n)/(n+1)

Martin Ender

Posted 2015-12-09T17:39:41.920

Reputation: 184 808

1

Jolf, 15 13 bytes

Try it here: ze link. You know what? I almost implemented a built-in. I just didn't have time. Le sigh. Also, there's a bug with my combination code, so I have to implement it with permutations. >_< I'm now also pretty glad I didn't add comments.

//mk*2jjm!jhj

With permutation (9 bytes; invalid, as I fixed this after the challenge was posted):

/mK*2jjhj

With built-in (3 bytes; implemented after challenge :P. I take off my hat to @FlagAsSpam.):

m$j

Conor O'Brien

Posted 2015-12-09T17:39:41.920

Reputation: 36 228

1wow r u le french? – Adnan – 2015-12-09T23:01:01.493

2@Adnan XD I'm taking french, but that's about as far as it goes – Conor O'Brien – 2015-12-09T23:01:32.663

1

Pari/GP, 17 bytes

n->(2*n)!/n!/n++!

Try it online!

alephalpha

Posted 2015-12-09T17:39:41.920

Reputation: 23 988

1

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

Vasu Adari

Posted 2015-12-09T17:39:41.920

Reputation: 941

1

Maple, 18 bytes

(2*n)!/((n+1)!*n!)

Usage:

> f := n->(2*n)!/((n+1)!*n!);
> f(19);
  1767263190

DSkoog

Posted 2015-12-09T17:39:41.920

Reputation: 560

0

Clojure, 45 bytes

#(apply *(for[k(range 2(inc %))](/(+ % k)k)))

Uses the direct formula instead of recursion. Luckily * with zero arguments returns one :)

NikoNyrh

Posted 2015-12-09T17:39:41.920

Reputation: 2 361

0

cQuents, 13 bytes

f2$)/(f$+1)f$

1-indexed. Try it online!

Explanation

:                 Implicit; sets mode to sequence
                  Given input n, output nth term in sequence; otherwise, output sequence
                  Each term in the sequence is equal to:
 f2$)             Factorial (2 * current)
     /            Divided by
      (        )  Group (implicit )
       f$+1)      Factorial (current + 1)
                  Implicit multiplication
            f$)   Factorial (current, implicit )

Stephen

Posted 2015-12-09T17:39:41.920

Reputation: 12 293

0

Excel, 23 bytes

Unimaginative answer:

=COMBIN(2*A1,A1)/(A1+1)

Wernisch

Posted 2015-12-09T17:39:41.920

Reputation: 2 534

0

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

Leaky Nun

Posted 2015-12-09T17:39:41.920

Reputation: 45 011

0

Lua, 86 bytes

c=setmetatable({[0]=1},{__index=function(c,n)c[n]=c[n-1]*(4-(6/(n+1)))print(c[n])end})

Try it online!

MCAdventure10

Posted 2015-12-09T17:39:41.920

Reputation: 103

0

Pyt, 1 byte

Ć

Gets the input n implicity, then uses a builtin to get the nth Catalan number

Try it online!

mudkip201

Posted 2015-12-09T17:39:41.920

Reputation: 833

0

Brain-Flak, 78 bytes

(([{}])<(({}){}){({}()<(())<>{({}({})<>)<>}>)}><>){({}()<{}>)}{}({}[{}]<>{}{})

Try it online!

Computes the first 2n rows of Pascal's triangle, then returns ((2n-1) C n) - ((2n-1) C (n+1)).

Nitrodon

Posted 2015-12-09T17:39:41.920

Reputation: 9 181

0

Python 3, 83 63 62 55 bytes

With thanks to Thomas Kwa.

f=lambda x:x<1or x*f(x-1)
c=lambda n:f(2*n)/f(n)/f(n+1)

f is the factorial function. c returns what is equivalent to 2*n C n divided by n+1.

Sherlock9

Posted 2015-12-09T17:39:41.920

Reputation: 11 664

Thanks @ThomasKwa. Where were you when I got stuck on the Bernoulli numbers question? :D – Sherlock9 – 2015-12-09T18:59:57.840

0

Jellyfish, 16 12 bytes

p
%C+
 &
>+i

Try it online!

Leaky Nun

Posted 2015-12-09T17:39:41.920

Reputation: 45 011

Another 12-byte solution: http://jellyfish.tryitonline.net/#code=cAolKEMKICYKPitp&input=MTk

– Martin Ender – 2016-08-05T06:20:52.153

0

><>, 29+2 = 31 bytes

:1+$?!\:2-
$/?=1l<*-$4,$6
;\n

Requires the input to be present on the stack at program start, so +2 bytes for the -v flag. Try it online!

Uses the algorithm presented in Stefano Sanfilippo's answer (linky).

The first line compiles n+1, n, n-1, ... , 2, 1 on the stack. The second line, running backwards, computes C(n) = (4 - (6 / (n+1)) * C(n-1). Each iteration reduces the size of the stack by 1, so the remaining number is output when the length of the stack is 1.

Sok

Posted 2015-12-09T17:39:41.920

Reputation: 5 592

0

Python 2, 92 bytes

(lambda f:lambda n:f(2*n)/f(n)/f(n+1))((lambda r:r(r))(lambda r:lambda x:x<1or x*r(r)(x-1)))

Ideone it!

This answer purely serves to demonstrate the power of lambdas.

Leaky Nun

Posted 2015-12-09T17:39:41.920

Reputation: 45 011