How do you implement the factorial function in C++ with proper error handling?
I asked this before but it was closed by people who didn't understand the question. I'开发者_JAVA技巧m not looking for just a loop, I am looking for how you would do it for production code with stuff like error handling for arguments and overflows.
And please don't just say "use library X" unless you can link to the code for said library and it actually addresses these concerns.
Use table lookup. You won't need big table, since factorial will overflow 64 bit double precision variable range very quickly. You only need to store function values for argument values from 0 to 170. Anything outside that range should generate an error.
It depends on the domain of the input.
If you are using a 32-bit or 64-bit integer, you shouldn't use a loop at all: just use a lookup table. There are not very many n
for which n!
is representable by a 64-bit integer. With a lookup table, checking for overflow is easy: if there isn't an entry for n
in the lookup table, it's obviously out of range.
If the input is larger than that then presumably you will be using some sort of "big integer" class and overflow is unlikely to be an issue.
Might be something as simple as:
unsigned factorial(unsigned n)
{
if (n > theUpperThreshold)
throw ExceptionFormYourMathLibrary("Explain that n! can't be represented by unsigned");
return lookupTable[n];
}
Unless your math library provides some big integer class as well.
精彩评论