c++ - Faculty and factors with recursion -


i'm trying implement recursion in different way, i'm stumped implementation of said math.

here's code:

#include <iostream> using namespace std;    template <const int n> class faculty { public:     static const int val = faculty<n - 1>::val * n; //recursion!!!! };   //for when 1!, return value of 1! template <> class faculty<1> { public:     static const int val = 1; };   //falling factorial template <const int n, const int k> class fallingcfactorial { public:     static const int n_k = faculty<n>::val / faculty<n - k>::val;     // (n * n - 1 * ... * 1) / ((n - k) * (n - k + 1) * ... * 1) };    // implementing factorial different way // (n * (n - 1) * ... * (n - k + 1))   //for when n = k output = 1 template <const int n> class fallingcfactorial<n, n> { public:     static const int n_k = 1;  };   int main(void) {     cout << "faculty of 5 (1*2*3*4*5): " << faculty<5>::val << endl;     cout << "n(10)_k(5) = " << fallingcfactorial<10, 5>::n_k << endl; } 

trying (n * (n - 1) * ... * (n - k + 1)) way, fail @ implementing in code. math isn't absolute strong suit, ok.

the use of templates little bit tricky. think should solve problem:

#include <iostream> using namespace std;  template <const int n, const int k> class fallingfactorial { public:     static const int n_k = fallingfactorial<n - 1, k>::n_k * n; };  template <const int n> class fallingfactorial<n, n> { public:     static const int n_k = 1; };  int main(void) {     cout << fallingfactorial<10, 5>::n_k << endl;     return 0; } 

this example based on partial template specialization (template <const int n> class fallingfactorial<n, n>). when template class called best matching , "most specialized" template used. older compilers doesn't support partial specialization (see wiki).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -