Android Code Snippet Factorial Function (!n)

ilan

Expert
Licensed User
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:

ilan

Expert
Licensed 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 :)
 

advansis

Active Member
Licensed 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
 

advansis

Active Member
Licensed 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
 
Top