# Android Code SnippetFactorial Function (!n)

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

##### B4X founder
Staff member
Longtime User
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
Longtime User
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

##### Expert
Longtime User
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
Longtime User
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

##### B4X founder
Staff member
Longtime User
Recursion in very elegant, but, in my own opinion, usually are not efficient
You cannot talk about efficiency without a real context. It doesn't matter whether a task takes 0.2ms or 0.4ms. Recursion is a very important tool. Like all tools it has its advantages and disadvantages.

##### Active Member
Longtime User
You cannot talk about efficiency without a real context. It doesn't matter whether a task takes 0.2ms or 0.4ms. Recursion is a very important tool. Like all tools it has its advantages and disadvantages.
You are right, Erel. Anyway, when possible I prefer the straigth-way. ;-) Recursion is sometimes misused

Replies
10
Views
6K
Android Code Snippet NB6 class - additional functions
Replies
11
Views
9K
Replies
7
Views
4K
Replies
1
Views
3K
Replies
1K
Views
266K