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!