I'm trying to implement the recursion in a slightly different way, but I'm stumped as to the implementation of said math.
Here's my 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 the Factorial a different way
// (n * (n - 1) * ... * (n - k + 1))
//For when n = k then 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 to do it (n * (n - 1) * ... * (n - k + 1)) way, I fail at implementing it in code. Math isn't my absolute strong suit, but I do ok.
The use of templates it a little bit tricky. I think this should solve your 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 is based on partial template specialization (template <const int n> class fallingFactorial<n, n>). When a template class is called the best matching and "most specialized" template is used. Some older compilers doesn't support partial specialization well (see wiki).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With