+ 2
why is the cout to this code 10? can someone explain the steps to the result?
#include <iostream> #include <cstdlib> using namespace std; int f (int a, int b) { if(a==0||b==0||a==b) { return 1; } else { return f(a-1, b-1) + f(a-1, b); } } int main() { cout<< f(5,3) << endl; return EXIT_SUCCESS; }
2 Réponses
+ 18
+ 6
We can just calculate it by mathematical way.
f(5,3)=f(4,3)+f(4,2)
f(4,3)=f(3,3)+f(3,2)=1+f(3,2)
f(3,2)=f(2,2)+f(2,1)=1+f(2,1)
f(2,1)=f(1,1)+f(1,0)=1+1=2
So f(4,3)=1+1+2=4
f(4,2)=f(3,2)+f(3,1)
f(3,2)=3 (as above)
f(3,1)=f(2,1)+f(2,0)=1+f(2,1)=1+2 (as above)
=3
So f(4,2)=3+3=6
So the result f(5,3)=f(4,3)+f(4,2)=4+6=10
+This is well known as a code calculating combination. This represents the number of way choosing (k) things from (n) things without an order. By using famous property of combination, C(n,k)=C(n-1,k)+C(n-1,k-1), we can make code in the question. For more information about combination, go to Wikipedia.
Wikipedia: https://en.wikipedia.org/wiki/Combination