Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Visual Basic (http://www.programmingforums.org/forum18.html)
-   -   For Loops And Variables (http://www.programmingforums.org/showthread.php?t=683)

Johnny_English Sep 29th, 2004 9:24 AM

Public Function primechk(max As Integer)
I'm still writing the prime number algorithm and so far I have this code for my function:

:

Dim primes() As Integer
ReDim primes(0)
primes(0) = 2
For x = 3 To max
  bound = UBound(primes)
  For index = 0 To bound
    If x Mod primes(index) = 0 Then
      Exit For
    End If
    indices = index
  Next index
  If indices = bound Then
    ReDim Preserve primes(bound + 1)
    primes(bound + 1) = x
  End If
 
Next x
  Print primes(bound)
End Function

It works fine, but I'm still optimizing, before I was using this:

:

For index = 0 To bound
    If x Mod primes(index) = 0 Then
      Exit For
    End If
    If index = bound Then
      ReDim Preserve primes(bound + 1)
      primes(bound + 1) = x
    End If
Next index

But I realized that checking the index each iteration was very inefficient, so I decided to put the If then statement outside the embeded for loop:

:

Next index
  If index = bound Then
    ReDim Preserve primes(bound + 1)
    primes(bound + 1) = x
  End If
 
Next x


Unfortunately, the program was not working... After a quick print test with the variable index, I came to the realization that it was destroyed as soon as the loop exited. So I decided to use the sligtly more efficient

:

For index = 0 To bound
    If x Mod primes(index) = 0 Then
      Exit For
    End If
    indices = index
  Next index


It's deffinetly better than repeating the if then and comparisons. But I still feel that the assignment is taking up too much time. In order to make this program truly optimized I want to reuse index.

How do I keep the variable index from being destroyed after the loop is exited so I can reuse its value later?

Thanks!

Berto Sep 29th, 2004 10:09 AM

If ou declare a variable inside a loop it only remains for the scope of the
loop, so i would decalre it at the start of the method or make it a gloabal variabel <--- not a good idea to do that one,.


All times are GMT -5. The time now is 11:10 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC