Android Code Snippet Factorial Function (!n)

Discussion in 'Code Snippets' started by ilan, Apr 16, 2019.

  1. ilan

    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.

    Code:
    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:

    Code:
    Log(factorial(6))
     
    Last edited: Apr 16, 2019
  2. Erel

    Erel Administrator Staff Member Licensed User

    Your code is better but it is still worth posting the recursive version as it is quite nice:
    Code:
    Sub Factorial(Number As Int) As Int
     
    If Number = 1 Then Return 1
     
    Return Number * Factorial(Number - 1)
    End Sub
     
  3. ilan

    ilan Expert Licensed User

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

    JordiCP Well-Known Member Licensed User

    As factorial is defined for n>=0 but still 0!=1, it should be (for non-negative numbers) ;)
    Code:
    Sub Factorial(Number As Int) As Int
     
    If Number=0 Then Return 1
     
    Return Number * Factorial(Number - 1)
    End Sub
     
  5. advansis

    advansis 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
     
  6. Erel

    Erel Administrator Staff 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.
     
    wonder likes this.
  7. advansis

    advansis Member Licensed User

    You are right, Erel. Anyway, when possible I prefer the straigth-way. ;-) Recursion is sometimes misused
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice