Professor Java
Your Ad Here

Factorial/Binomial Coefficient Calculator:

N: K:


Note: to find n!, set k=fac.

Factorial/Binomial Coefficent (N Choose K)

public static long factorial(int a){ //non-recursive factorial, returns long
    int answer=1; 
    for(int i=1;i<=a;i++){ //starts from 1, multiplies up, such as 1*2*3...
  public static long recFactorial(int a){ //recurive factorial, returns long
    if(a==1){ //stopping case for recursion: if a=1; 1!=1.
    return(a*recFactorial(a-1)); //recursion: a!=a*(a-1)!
  public static long comboChoose(int n, int k){ //combinatorics function. takes n,k
    return(factorial(n)/(factorial(k)*factorial(n-k))); //definition of nCk.

Three functions above used to return factorial and the nCk function. More on that later, first lets focus on the two factorial functions. the first is straightforward, a for loop multiplies from 1*2*3....*a, returning the calculation. The second function is recursive, and other than to show the use of recursion, don't ever use this function. It gets unbearably slow as a increases; it is implemented by the fact that
n!=n*(n-1)!. However, it becomes slow because 4!=4*3!, but they must find 3!, which is 3*2!, and 2!, which is 2*1!. Then, it returns 1! to 2, returning 2!, and so on, as the stack becomes very large and inefficient.
The third function is a combinatorics function used commonly in mathematical "counting" problems, such as the ways for 3 people to pick 5 coats. It is commonly called n choose k, nCk for short, or the binomial coefficient, because it shows up as the constants in expansions of (x-1)^n. Here is the definition:
and the comboChoose method, really only a line long, implements this definition with calls to factorial, so make sure to include the factorial function if used the comboChoose function in your programs.
Implementation in javascript above, note that for normal nCk, just input the numbers normally; for n!, put in the value of n and write "fac" without the quotations where you would normally write k.
Provided by site.
Your Ad Here