Qbasicnews.com

Full Version: VB recursion error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Code:
Function factorial(n As Double) As Double
If n < 2 Then
  factorial = 1
Else
  factorial = n * factorial(n - 1)
End if
End Function
That's my recursive factorial-figurer. But when I try to use it to calculate even the smallest factorials, like 3! or 4!, I get the runtime error "Out of stack space".
Is it just my computer?
Two things:

1.- Maybe you need to set up an auxiliary variable to store the results, and then assign it to factorial (I'm not sure, but that's how I do it). Maybe that "factorial = 1" in the base case is doing nasty things (senseless calls and stuff).

2.- Upon the definition of factorial it only works with integer numbers, so it would be less correct to use LONGs (you can use Doubles if you are careful enough not to send decimal numbers to the function).

Code:
Function factorial(n As Long) As Long
   Dim res As Long
   If n < 2 Then
      res = 1
   Else
      res = n * factorial(n - 1)
   End if
   factorial = res
End Function
VB doesn't have a very large stack... :-?

Anyway, why do you need a recursive function to calculate the factorials?

Can't you just do this:
Code:
Private Function Fac (n As Integer) As Long
   If n <= 1 Then Fac = 1: Exit Function
   Dim lngRes As Long, intT As Integer
   lngRes = 1
   For intT = 2 To n
      lngRes = lngRes * intT
   Next intT
   Fac = lngRes
End Function
Works faster and cleaner and doesn't need as much stack space as the recursive function Smile
Neo: True, true, but I wanted for practice in computer sci to write this thing.
In QB, isn't there a command to allocate more stack space? Does that apply to QB as well?
[EDIT]Nath, thanks, doing that worked. [/EDIT]
I dunno whats wrong with our CP teacher as well. They insist on using recursion as well :???:
Recursion is very useful at times...for instance, walking a directory structure or writing a threaded forum.
In those cases Yes. But not in case of factorials and such stuff :wink:
Well, hey...it was in the vb textbook I'm studying, and I've encountered it before (recursion) and I never really understood it. So I thought, why not implement it in a *Very* easy language?
(I've done it in assembly before, a nightmare).
Quote:In those cases Yes. But not in case of factorials and such stuff :wink:

Well, that's only for educational purposes. Factorial is itself a really simple function to illustrate the base case and the recursive case, it is short, and can be understood easily.