Results 1 to 7 of 7

Thread: Various types of recursion

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Super Moderator Petr Schreiber's Avatar
    Join Date
    Aug 2005
    Location
    Brno - Czech Republic
    Posts
    7,129
    Rep Power
    732

    Various types of recursion

    Learning for exam,

    I had to create example on different kinds of recursion to really see they behave as described.
    Could serve as some kind of test whether recursion works ok:
    ' -- Various types of recursion
    
    Uses "Console"
    
    PrintL "Ackermann function"
    PrintL ack(3, 4)
    PrintL
    
    PrintL "Fibonacci"
    PrintL fib(5)
    PrintL
    
    PrintL "Factorial"
    PrintL fact(5)
    PrintL
    
    PrintL "Greatest common divisor"
    PrintL gcd(513, 27)
    PrintL
    
    WaitKey
    
    ' -- Nested recursion: Recursive call to function contains recursive call to itself in the arguments
    ' -- Ackermann function
    Function ack(x As Number, y As Number) As Number
     If x = 0 Then Return y+1
     If y = 0 Then Return ack(x-1, 1) 
     Return ack(x-1, ack(x, y-1))
    End Function
    
    ' -- Cascade (tree) recursion: Multiple occuriences of recursive call appear in one expression, but without any nesting
    ' -- Fibonacci
    Function fib(n As Number) As Number
     If n <= 1 Then Return 1 
     Return fib(n-2)+fib(n-1)
    End Function
    
    ' -- Linear recursion: Each alternative of definition contains 1 recursive call at max.
    ' -- Factorial
    Function fact(n As Number) As Number
     If n = 0 Then Return 1 
     Return n * fact(n-1)
    End Function
    
    ' -- End recursion: Special case of linear recursion, where recursive call is the last operation of specific alternative of definition
    ' -- Greatest common divisor
    Function gcd(x As Number, y As Number) As Number
     If x = y Then Return x
     If x > y Then Return gcd(x-y, y)
     Return gcd(x, y-x)
    End Function
    
    You can take a walk through the code using debugger, to watch it call itself.


    Petr
    Last edited by ErosOlmi; 21-01-2011 at 00:37.
    Learn 3D graphics with ThinBASIC, learn TBGL!
    Windows 10 64bit - Intel Core i5-3350P @ 3.1GHz - 16 GB RAM - NVIDIA GeForce GTX 1050 Ti 4GB

Similar Threads

  1. Types
    By kryton9 in forum TBGL General
    Replies: 8
    Last Post: 26-11-2006, 00:36

Members who have read this thread: 0

There are no members to list at the moment.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •