recently I've been working on a library to handle very large numbers with thousands of digits. I have now worked on a factorial function for these things as I just set up multiplication.
largeNum factorial(largeNum& input) {
if (input > one) return (input * factorial(--input));
else return one;
}
"one" is a largeNum defined to have a value of"one" with a "+" sign since I haven't yet implemented integer conversion.
Factorial is a friend function of the largeNum class. I do not get any syntax errors, it has to be logical.
The prefix -- operator is properly overloaded and also tested.
So are multiplication and the ">" operator.
Maybe I'm just being plain blind as I'm a little sleep deprived but I need some help here. Cheers.
To answer your question: the "unexpected" results, i.e. "entering 5 gives 4!, not 5!", has to do with undefined behaviour introduced by the following line of code:
input * factorial(--input)
Note that the order of evaluation of operators in C++ is mostly undefined (cf., for example, cppreference). So it may happen that factorial(--input)
is evaluated before it's result is multiplied by the (in the meanwhile changed?) value of input
. In conjunction with side effects, where an operation alters the same (or an other) object, this usually results in undefined behaviour when the same (or the other) object is used in the same expression without having a sequence point in between. Just as operation n = ++i + i;
is UB (cf. evaluation order / undefined behaviour).
Hence, this code may sometimes behave as you expect, but may also behave completely different.
So if --input
has side effects on the contents of input
(as we may asume), then your code has to be rewritten to
input * factorial(input-one)
where (input - one)
must not alter input
in any way (and has to be implemented such that it gives the correct result, of course).