Write a recursive function that calculates the binomial coefficient.
\(C_n^p=\frac{n!}{(n-p)!\times p!}\)
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
int factrec(int n)
{
if (n <= 1)
return 1;
return n * factrec(n-1);
}
int binomialrec(int n, int p)
{
return factrec(n)/(factrec(p)*factrec(n-p));
}
void main()
{
int p,n;
printf("n : ");
scanf("%d", &n);
printf("p : ");
scanf("%d", &p);
printf("Version 1 : C_^%d_%d = %d\n", p, n, binomialrec(n, p));
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Static Binary Search Trees