The Programming Project: Binomial Coefficient
Showing posts with label Binomial Coefficient. Show all posts
Showing posts with label Binomial Coefficient. Show all posts

Thursday, April 17, 2014

Binomial Coefficient using recursion in Python and C language





C Code
#include<stdio.h>
long int Binomial(long int, long int);
int main()
    {
    long int n,k;
    printf("\n Enter the value of n and k, n is greater than k:");
    scanf("%ld %ld",&n,&k);
    while( k < 0 || n < 1 || k > n) {
        printf("\n Wrong input, enter again:");
        scanf("%ld %ld",&n,&k);
        }
    printf("\n Value of %ldC%ld: %ld \n", n,k,Binomial(n,k));
    return 0;
    }
long int Binomial(long int n, long int k)
    {
    return (k <= 1 ? (k == 0 ? 1 : n) : (n*Binomial(n-1,k-1))/k);
    } 


Python Code
 
#File: binomial.py
#A simple program to calculate nCk using recursion
def main():
    print "Binomial Coefficient"
    n = input("Enter the value of n:")
    k = input("Enter the value of k:")
    x,y= n,k
    def binomial(n,k):
        if k < 2:
            if k == 1:
                return n
            else:
                return 1
        else:
            return (n*binomial(n-1,k-1))/k
   
    print "Value of nCk is",binomial(x,y)
   
main()


OUTPUT:

administrator@ubuntu:~/python$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import binomial
Binomial Coefficient
Enter the value of n:1200
Enter the value of k:600
Value of nCk is 396509646226102014036716014862605729531608195706791651137874888645453416610941265150218719101931467943643355545203450497992759241509133380338379948816055787676920090991204851973167965845932778899299658455186568000803781988756668261491937388063732393433822461878746138860879613812823280622769290795808335597761702284943981759657834318699226167559487050708295600
>>>

/* To calculate the Binomial Coeffcient using recursion */
/* We have use the formula nCk = (n/k)*{(n-1)C(k-1)} */