Binomial coefficient in program description C

Therefore, I need to write a program that produces eleven binomial order coefficients. I stumbled upon this code that does what I need, but I'm trying to understand why it works.

#include<stdio.h> int binomialCoeff(int n, int k) { if(k == 0)return 1; if(n <= k) return 0; return (n*binomialCoeff(n-1,k-1))/k; } int main() { int k; for(k=10;k>=0;k-=1) { printf("%d\n", binomialCoeff(10, k)); } 

I understand why the main part of int works, I just don’t understand how binomialCoeff is calculated. I'm relatively new to all of this coding, so thanks for the help!

+5
source share
1 answer

It is actually quite elegant.

The binomialCoeff function is a recursive function with two basic conditions. If k == 0 , you return only 1 . If n<=k , you return 0. Therefore, if the value does not match true, you call the same function, subtracting it from n and k . This is repeated as a result.

n * (binomialCoeff (n-1, k-1)) / k

So N is 10 and K is 7

You are getting

  10*(binomialCoeff(9,6)/7) 

Just to keep things simple, call the first time binomialCoeff is called res1. This simplifies:

 10*(res1/6) 

but res1 itself calls binomialCoeff

as a result

  9*(binomialCoeff(8,5)/6) 

which we can call res2

therefore, we get

 10*(res2/6) 

and so on, until you meet the basic conditions; whereby the series n is multiplied together.

+5
source

Source: https://habr.com/ru/post/1241958/


All Articles