Thomas
Thomas

Reputation: 867

Out of stack space in vba when running code for project euler #1

Option Explicit
Sub peuler1()
Dim x As Variant
Dim y As Variant
y = 0
For x = 1 To 999
    If x Mod 3 = 0 Or x Mod 5 = 0 Then
    y = y + x
    End If
Next x
Call peuler1
End Sub

Why is this taking so long? it doesn't seem to be too convoluted.

Upvotes: 1

Views: 973

Answers (5)

PowerUser
PowerUser

Reputation: 11791

How about this?

Option Explicit 
Function peuler1() as integer
   Dim x As integer
   Dim y As integer 
   y = 0 
   For x = 1 To 999 
      If x Mod 3 = 0 Or x Mod 5 = 0 Then y = y + x 
   Next x 
   pueler1=y
End Sub 

This procedure is a function, which means it returns a value (Subs do stuff. Functions calculate something). Adding peuler1=y at the bottom makes the function return the value of y. The advantage of this is that you can now call this procedure from another procedure.

If you are working on this in the standard MS Office VBA Editor, you can get your answer by typing debug.print peuler1 in the Immmediate window.

Upvotes: 1

rick schott
rick schott

Reputation: 21137

I believe you are in a recursive loop.

Remove Call peuler1

Upvotes: 8

CanSpice
CanSpice

Reputation: 35818

Move the Call peuler1 outside of the End Sub. You're calling peuler1 when you get to the end of peuler1, and never get to the end of it.

Upvotes: 0

Jack
Jack

Reputation: 133609

Because you seem to call function peuler1 inside its definition, you then keep going recursively until you fill up stack space.

(I don't use visual basic, just a guess)

Upvotes: 1

Adam
Adam

Reputation: 12680

You are calling your subroutine from within itself. That's going to give you an infinite loop.

Upvotes: 1

Related Questions