Login Register






Recursive Fib Sequence Generation filter_list
Author
Message
Recursive Fib Sequence Generation #1
Here's something I wrote just now to test recursion in batch. Recursion only happens if the count passed to the function is greater than or equal to 3 however.

Code:
@echo off & setlocal enabledelayedexpansion call :fib 47 goto :eof :: ---------------------------------------- :: write out n count of the fib sequence :: accurate up to n = 47 :: ---------------------------------------- :fib if [%1]==[] goto :eof if %1==0 goto :eof if %1 GEQ 1 echo 0& if %1 GEQ 2 echo 1 if %1 LSS 3 goto :eof set /a n=%1-2 set a=0 set b=1 :fib_recur set /a fib_num=!a!+!b!&echo !fib_num! set /a n-=1& if !n!==0 goto :eof set a=%b%& set b=%fib_num% call :fib_recur %a% %b%

Output:
Code:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903

Lol, the limit for recursion in batch isn't the greatest, but if you exceed the limit and end up using too much of the stack before the recursion starts to crawl back up, you'll get a nice friendly message:
[Image: 2SWbl1e.png]

Reply