lettura simple

How to find factorial in Octave

In this lesson I will explain how to calculate the factorial number in Octave

What is factorial number? The factorial of a positive integer n≥0 is the product of the number and the integers from (n-1) to 1. $$ n! = n \cdot (n-1) \cdot (n-2) \cdot \dots \cdot 2 \cdot 1 $$ To indicate the factorial of a number we use the symbol n! The value of 0! is 1, according to the convention for an empty product.

To calculate the factorial number n! in Octave you can use factorial() function

factorial(n)

The parameter n is a non-negative integer (n≥0)

For example, type factorial(3) to calculate the factorial 3!

>> factorial(3)

The factorial of 3 is 6

ans = 6

It is 3!=6, because the product

$$ 3! = 3 \cdot 2 \cdot 1 = 6 $$

Now, type factorial(4) to calculate the factorial 4!

>> factorial(4)

The factorial of 4 is 24

ans = 24

It is 4!=24, because the product

$$ 4! = 4 \cdot 3 \cdot 2 \cdot 1 = 24 $$

If you try to calculate the factorial of zero

>> factorial(0)

The factorial 0! is equal to 1 by definition

ans = 1

Thus, the factorial 0! and the factorial 1! are both equal to 1.

$$ 0! = 1! = 1 $$

Note. In Octave you can calculate the factorial number also by defining a custom function. However, since there is already the default factorial() function, it is much more convenient to use it.

Remember that you can calculate the factorial only of non-negative integers.

If you try to calculate the factorial of a negative number Octave returns an error

>> factorial(-1)
error: factorial: all N must be real non-negative integers
error: called from
factorial at line 40 column 5

Octave also fails if you try to calculate the factorial of a real number

>> factorial(3.1)
error: factorial: all N must be real non-negative integers
error: called from
factorial at line 40 column 5




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin