Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing the factorial of a small integer at compile time

I just implemented (once again) a recursive template for computing the factorial of an integer at compile time (who would had thought that some day I'll actually need it!). Still, instead of rolling my own, I went to Boost looking for an answer. However, the factorial function in special math specifically forbids its use with integer types, so I just wrote my own.

Still, is there another function in Boost that I should use? Should I cast my integer to double and use the boost::factorial function? Is the computation performed at compile time?

like image 807
gnzlbg Avatar asked Jul 31 '12 17:07

gnzlbg


People also ask

What is the factorial of an integer?

factorial, in mathematics, the product of all positive integers less than or equal to a given positive integer and denoted by that integer and an exclamation point. Thus, factorial seven is written 7!, meaning 1 × 2 × 3 × 4 × 5 × 6 × 7. Factorial zero is defined as equal to 1.

How do you find the factorial of a number?

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 is 1*2*3*4*5*6 = 720 .


1 Answers

You don't need Boost, this is just 1-liner if you have C++11:

constexpr uint64_t factorial(uint64_t n) { 
    return n == 0 ? 1  :  n * factorial(n-1); 
}

And it will work even if your arg is not compile time constant too. uint64_t will work with n < 21.

If you are doing it in compile time and multiply with floating point value - there will be no conversion overhead (conversion will be at compile time too).

like image 145
Leonid Volnitsky Avatar answered Oct 06 '22 00:10

Leonid Volnitsky