Solution 5

Main | Review of Operators | Mathematical Functions | Practice 5 | Solution 5 | HTML Forms | PHP Forms | Practice 6 | Solution 6 | PHP and E-mail | Practice 7 | Solution 7

Here is a solution to practice 5:

function factorial_iterative($n) 
{
  $answer = 1;
  while($n > 0)
    $answer *= $n--;
  return $answer;
}

function factorial_recursive($n)
{
  if ($n == 1) return 1;
  if ($n > 1)  return $n * factorial_recursive($n-1);
}

print factorial_iterative(5);
print "<br>";
print factorial_recursive(5);

Note that you might have a different solution, but I imagine that it will be similar. Note the following statement within the factorial_iterative() function:

    $answer *= $n--;

The above is the same as saying:

   $answer = $answer * $n;
   $n--;

Except it takes advantage of the flexibility of the assignment operator. Note also that the statement $n-- uses the current value of $n before doing the multiplication operation and then decrements it, so you can get away with doing the above with one line as the solution has. If you wanted the value of $n to subtracted before you did the multiplication you could type --$n. These details can result in compact notation which you might see when you are programming with others, but they are not essential to the task of defining a factorial function.

The recursive version of the function is included. Notice that the recursive code is simpler and that it follows the original formal definition of factorial given before:

n! = {n*(n-1)! if n > 1 OR 1 if n = 1

If you had trouble with the recursive version of the function don't worry. It is included more as an extra than an essential feature of PHP. It is most important that you be able to decompose a problem into the tools that PHP makes available to you. The rest of this tutorial will focus on practical applications of PHP, particularly online forms.


jfulton [at] member.fsf.org
22 Aug 2013