@amora , I’ll try to describe the fact()
function in more detail. By the way, since the task states that n
and m
are nonnegative integers , we will also make a function for them, not for float
.
To start. Record:
unsigned int fact (unsigned int q) { return !q ? 1 : q * fact(q - 1); }
it's just an abbreviated form like this:
unsigned int fact (unsigned int q) { if (q == 0) // проверка, соответствующая !q return 1; // это часть перед ":" в тернарном операторе в return !q ? 1 : ... else return q * fact(q - 1); // естественно, правая, т.е. после ":" часть }
more familiar (yet for you) recording of the same algorithm.
I think that the algorithm itself after such a record n! :
n! = n * (n - 1) * (n - 2) * ... * 2 * 1 * 1
(in fact, I just flipped the entry from the @paulgri comment) obvious.
Now let's look at a short example of what happens during recursion. Time flows from left to right, and the stack of function activations grows from top to bottom. Variables I replace them with values.
main: func(3) оп-па результат 3! == 6 func: 3 * func(2) return 3 * 2 func: 2 * func(1) return 2 * 1 func: 1 * func(0) return 1 * 1 func: return 1
This is how the recursive version of the factorial function works.
It is clear that already with a small value of n
overflow will arise in the course of the calculations. The result of the next multiplication will not fit into 32 bits of the unsigned int
type. The delay to the unsigned long long
type (64 bits) returned by the function will be somewhat delayed. Those. Here is her view:
unsigned long long fact(unsigned int q) { return q ? q * fact( q - 1) : 1; }
somewhat more satisfy our curiosity.
(replacing! q? on q? doesn’t change anything by itself, it’s just that IMHO looks prettier).
func(float)
from the question looks strange. - I rummaged a bit in Google and found that Factorial of a real number also exists, which is calculated by the formula: X! = N! * ((N + 1) ** d) N - the integer part of the number X d - the mantissa of the number X @amora, in principle, what is needed for your task? - avp