logo CodeStepByStep logo


Language/Type: PHP recursion

Write a recursive function named factorial that accepts an integer $n as a parameter and returns !$n, the factorial of $n.

A factorial of an integer is defined as the product of all integers from 1 through that integer inclusive. For example, the call of factorial(4) should return 1 * 2 * 3 * 4, or 24. The factorial of 0 and 1 are defined to be 1.

If passed a negative value, your function should throw an Exception. You may assume that the value passed is non-negative and that its factorial can fit in the range of type Integer.


  • Do not declare any global variables.
  • Do not use any loops; you must use recursion.
  • Do not use any auxiliary data structures (e.g. arrays) or strings to solve this problem.
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.