함수 nCr()

1 개요[ | ]

함수 nCr()
  • 조합의 수를 구하는 함수

2 C++[ | ]

C++
Copy
#include <iostream>
using namespace std;

long nCr(int n, int r) {
    r = min(r, n-r);
    long ret = 1;
    for(int i=1; i<=r; i++) {
        ret = ret * (n-i+1) / i;
    }
    return ret;
}

int main() {
    cout << nCr(2,2) << endl;    // 1
    cout << nCr(3,2) << endl;    // 3
    cout << nCr(4,2) << endl;    // 6
    cout << nCr(5,2) << endl;    // 10
    cout << nCr(100,5) << endl;  // 75287520
    cout << nCr(1000,5) << endl; // 8250291250200
}
Loading

3 Java[ | ]

Java
Copy
class App {
    static long nCr(int n, int r){
        r = (r < n-r) ? r : n-r;
		long ret = 1;
		for(int i=1; i<=r; i++) {
		    ret = ret * (n-i+1)/i;
		}
		return ret;
	}
	
	public static void main(String args[]){
		System.out.println(nCr(2,2));      // 1
		System.out.println(nCr(3,2));      // 3
		System.out.println(nCr(4,2));      // 6
		System.out.println(nCr(5,2));      // 10
		System.out.println(nCr(100,5));    // 75287520
		System.out.println(nCr(1000,5));   // 8250291250200
		System.out.println(nCr(10000,5));  // 832500291625002000
		System.out.println(nCr(100000,5)); // 1057310716455370528
	}
}
Loading
Java
Copy
public class MyClass {
    static int fact(int n) {
        int res = 1;
        for(int i=2; i<=n; i++) res *= i;
        return res;
    }
	static int nCr(int n, int r){
		return fact(n)/fact(r)/fact(n-r);
	}
	public static void main(String args[]){
		System.out.println(nCr(2,1)); // 2
		System.out.println(nCr(2,2)); // 1
		System.out.println(nCr(3,2)); // 3
		System.out.println(nCr(4,2)); // 6
		System.out.println(nCr(5,2)); // 10
		System.out.println(nCr(52,5)); // java.lang.ArithmeticException: / by zero
	}
}

4 PHP[ | ]

PHP
Copy
function nCr($n, $r) {
    if( $r > $n ) return -1;
    if( $r == 0 ) return 1;
    if( $n == $r ) return 1;
    if( $n-$r<$r ) $r=$n-$r;
    $res = 1;
    for($i=1; $i<=$r; $i++) $res*=($n-$i+1)/$i;
    return $res;
}
echo nCr(1,2) ."\n";     # -1
echo nCr(2,2) ."\n";     # 1
echo nCr(3,2) ."\n";     # 3
echo nCr(4,2) ."\n";     # 6
echo nCr(5,2) ."\n";     # 10
echo nCr(1000,5) ."\n";  # 8250291250200
Loading

5 Python[ | ]

Python
Copy
import operator as op
from functools import reduce
def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer / denom

print(ncr(2,1))   # 2.0
print(ncr(2,2))   # 1.0
print(ncr(3,2))   # 3.0
print(ncr(4,2))   # 6.0
print(ncr(5,2))   # 10.0
print(ncr(52,5))  # 2598960.0
Loading

6 R[ | ]

R
Copy
choose(1,2)      ## [1] 0
choose(2,2)      ## [1] 1
choose(3,2)      ## [1] 3
choose(4,2)      ## [1] 6
choose(5,2)      ## [1] 10
choose(100,5)    ## [1] 9034502400
choose(1000,5)   ## [1] 8.250291e+12
choose(10000,5)  ## [1] 8.325003e+17
Loading

7 같이 보기[ | ]