# Android Code SnippetFactorial Function (!n)

#### ilan

##### Expert
i had to get the factorial of a number but could not find a buildin function in b4x so i created a function for that.

B4X:
``````Sub factorial(number As Int) As Int
Dim returnNr As Int = number
Do Until number <= 1
number = number - 1
returnNr = returnNr * number
Loop
Return returnNr
End Sub``````
use:

B4X:
``Log(factorial(6))``

Last edited:

#### Erel

Staff member
Your code is better but it is still worth posting the recursive version as it is quite nice:
B4X:
``````Sub Factorial(Number As Int) As Int
If Number = 1 Then Return 1
Return Number * Factorial(Number - 1)
End Sub``````

#### ilan

##### Expert
Your code is better but it is still worth posting the recursive version as it is quite nice:
B4X:
``````Sub Factorial(Number As Int) As Int
If Number = 1 Then Return 1
Return Number * Factorial(Number - 1)
End Sub``````
really cool, i didnot knew that it is possible to do that with b4x. very smart coding #### JordiCP

##### Well-Known Member
As factorial is defined for n>=0 but still 0!=1, it should be (for non-negative numbers) B4X:
``````Sub Factorial(Number As Int) As Int
If Number=0 Then Return 1
Return Number * Factorial(Number - 1)
End Sub``````

##### Active Member
I prefer non-recursive functions, in this case is very simple to enroll it. Recursive functions increase memory and stack usage. Recursion in very elegant, but, in my own opinion, usually are not efficient

#### Erel

Staff member
• 