Really easy C++ programming question

  • Thread starter Thread starter Erica
  • Start date Start date
Joined
1/9/07
Messages
32
Points
16
How does one represent n! in C++?

There's got to be a more direct way than creating a loop.

If it's relavant to the answer, I am creating templates for calculating probability density functions. I am aware that I can calculate these in Excel using built in functions but what fun would that be?

I looked in math.h, but couldn't find what I was looking for.

Thanks in advance.
 
Erica,

To my knowledge, there is no factorial function or operator native to C++. If you want to compute a factorial, you'll have to write a function for it yourself. You can do this pretty easily with a loop or, if you're really determined to make life difficult for yourself, a recursive function.
 
Erica,

To my knowledge, there is no factorial function or operator native to C++. If you want to compute a factorial, you'll have to write a function for it yourself. You can do this pretty easily with a loop or, if you're really determined to make life difficult for yourself, a recursive function.

Actually the recursive function is the easiest way to do it.

Code:
double fact(const double& n)
{
    if (n <= 1.) return 1.;
    return n * factorial(n - 1.);
}

The main complain about this implementation is that it could overflow but any decent compiler will unwind the tail recursion.
 
You can use template metaprogramming to speed up the computation of factorials. This is advanced C++, though.

C++ Template Metaprogramming has an example.

If you are programming a more conventional factorial function, don't recurse or your stack may overflow. Use a loop. And make sure you don't overflow the int bounds and wind up with a garbage value. n! gets very large very quickly.
 
If you are programming a more conventional factorial function, don't recurse or your stack may overflow.
Indeed, the template version should be the best solution and, as I said before, any decent compiler should unwind the tail recursion and should not overflow the stack.
 
thanks all

I'l post my solution soon.

This community's sophisticated level of knowledge and absolute willingness to help never ceases to amaze me. Thanks again.

Have a great day and enjoy the dancing banana
:dance:
 
factorial overflow

using unsigned int (32 bits) this demonstrates how few factorials can be calculated before you overflow the supported range of numbers:

0! = 1
5! = 120
10! = 3628800
15! = 2004310016
18! = 3396534272
19! = 109641728



The template solution is good for wow! factor but not very practical in my view since it does not alow you to do:

unsigned int n(5);
unsigned int nfactorial = factorial<n>::value;

You have to know n at compile-time. Nice for constants that you use a lot, not for general usage. perhaps there is a way round this but I don't have time to look into it now.
 
Back
Top Bottom