# calculate the combinatorial [duplicate]

This question already has an answer here:

Given two integers - n and r, your task is to calculate the combinatorial nCr.

nCr = n! / r! (n-r)!


The caveat is that you have to write code to do this calculation in minimum number of characters.

Input The first line will be number of testcases T. Then T lines follow, each containing two positive integers - n and r.

output Print T lines, each line containing the value of nCr.

Constraints

1 <= T <= 100
1 <= r <= n <= 1000


You can assume that the value nCr will fit into a signed 64 bit integer.

## marked as duplicate by Peter Taylor, J B, John Dvorak, Gareth, HowardJan 7 '14 at 11:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

# Golfscript, 31 characters

n%(;{~.@.@-]{1\,{)*}/}%~/\/}%n*


Explanation:

• n/(;{...}%n* splits the input by a newline, discards the first row (number of testcases), maps the rest and finally joins by a newline.
• ~.@.@- evals the input, rearranges it to r n n r, then subtracts r from n.
• ]{...}%~ collects everything on the stack into and array, maps it and explodes the array
• 1\,{)*}/ is the factorial function: push a 1 below the number, then create an array 0...n, then for each element, multiply the accumulator by the value + 1. The map-reduce implementation is one char longer: ,{)}%{*}*
• /\/ divides n! first by factorial of the difference, then by r!.
• Hm, for input 1\n5 5\n I get  undefined method -' for nil:NilClass (NoMethodError). Am I misunderstanding the format of the input? :-/ – Joachim Isaksson Jan 7 '14 at 10:55
• no trailing newline please – John Dvorak Jan 7 '14 at 10:57
• Easily fixed by changing the first / to %`. – Peter Taylor Jan 7 '14 at 11:32
• Done, thanks. facepalm – John Dvorak Jan 7 '14 at 11:40