Android Code Snippet Factorial 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:

ilan

Expert
Licensed User
Longtime User

really cool, i didnot knew that it is possible to do that with b4x. very smart coding
 

advansis

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

advansis

Active Member
Licensed User
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
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…