Recursion with factorial

A recursive function is a procedure or subroutine, implemented in a programming language, whose implementation references itself.
It is really useful, try to make a program like Tower of Hanoi with an iterative algorithm… good luck !

So I will give you an easy method to create a recursive algorithm, I choose the example of factorial because of it simplicity.
Mathematical’s reminder : 4! = 4 * 3 * 2 * 1 = 24.

There are 3 steps :
– parameter(s) : identify all the parameters that you need to resolve the problem. They will decrease at each call of the function. In the factorial’s case, it is the factorial’s number.

function factorialCalculation(factorial:uint):uint

– exception’s case : this is when the procedure stops to call itself.

if (factorial == 1) { return 1; }

– recursive’s case : where recursive call is implemented, don’t forget to decrease (generally) parameter(s).

return factorial * factorialCalculation(factorial - 1);

Now all the code :

var factorial:uint = 4;
var resul:uint = 0;
 
resul = factorialCalculation(factorial);
 
function factorialCalculation(factorial:uint):uint {
 
	if (factorial == 1) {
		return 1;
	} else {
		return factorial*factorialCalculation(factorial-1);
	}
}

Be careful : recursive function are really heavy. Factorial’s case is just an easy example, it should be implemented as an interative function !

And for the fun with a ternary operation :

function factorialCalculation(factorial:uint):uint {
 
	return (factorial == 1) ? 1 : factorial * factorialCalculation(factorial - 1);
}

😀

Leave a Reply

Your email address will not be published. Required fields are marked *