Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Mathematics LibreTexts

4.5: Factorial Function

( \newcommand{\kernel}{\mathrm{null}\,}\)

Mathematically, we define the factorial as a function on a non-negative integer as

n!=n(n1)(n2)321


or the product of all of the numbers from itself down to 1. There are a number of ways to program this function as we will see. One way is

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

function fact(n::Integer) 
  local prod=1
  for i=1:n
    prod *= i 
  end
  prod
end
function fact(n::Integer) 
  local prod=1
  for i=1:n
    prod *= i 
  end
  prod
end
 

uses a for loop and we will see the details of this in Chapter XXX. The for loop first assigns i the value 1 then executes the lines, then sets the value to 2, then executes the block, and so on until i is n. Since prod starts as 1, this multiplies prod by every integer between 1 and n, and thus is the factorial. The result in prod is returned. 

For example, we can call the factorial function with an example like

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

factorial(10)
factorial(10)
 

Exercise

Try calling the factorial with a few other integers.  Include 0 and negative numbers as well. 


4.5: Factorial Function is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

Support Center

How can we help?