This article aims to show how you can create a simple function in Julia to get the factorial of a given number.
What is factorial?
The product of all integers equal to or less in value than the original number — in other words, a factorial is the number of possible combinations with numbers less than or equal to that number.
We symbolise the factorial of a number with “!” (e.g. 4!).
Logical zero factorial proof
As we said, a factorial is the number of possible combinations with numbers less than or equal to that number. Zero has no numbers less than it, but it is a number itself. How many arrangements can I do with 0 items? None at all. This is too a way of arrangement, so 0!=1 (none).
Suppose we have three fruits:
What are the arrangements?
3!=6 as we said previously.
Think similarly for 0!.
Function in Julia
function f(n::Int64) f = 1 if n < 0 print("Factorial does not exist for negative numbers") end if n == 0 print("The factorial of 0 is 1") end if n>0 for i in 1:n f = f*i end println("The factorial is: ",f) end end
Let’s ask the factorial of -3 (n=-3)
Factorial does not exist for negative numbers
Let’s ask the factorial of 0 (n=0)
The factorial of 0 is 1
Let’s ask the factorial of 3 (n=3)
The factorial is: 6
Let’s explain the part of the code below:
for i in 1:n f = f*i end
Firstly, we defined the f as 1.
So, we start with f=1.
for i in 1:3
- f=2*3=6 end
In this article, we gave a simple explanation of the factorial as well we made an easy function in Julia!
Thank you for reading!🤗