PDA

View Full Version : sieve of eratosthenes vba code explanation



wannabe11
10-27-2017, 12:51 PM
Hello Guys

i need some help in understanding the following vba code


Sub Sieve()
Const n As Long = 10 ' numbers to test
Dim colCand As Collection ' candidates
Dim aiPrim() As Long ' primes for output
Dim iPrim As Long ' a prime
Dim nPrim As Long ' running count of primes
Dim i As Long ' scratch index

Set colCand = New Collection
ReDim aiPrim(1 To n / (Log(n) - 2)) ' high estimate for nPrim

' initialize candidates
For i = 2 To n
colCand.Add Item:=i, Key:=CStr(i)
Next i

' we'll be trying to delete numbers in colCand that were already deleted
On Error Resume Next

Do While colCand.Count
' first number in colCand is a prime
nPrim = nPrim + 1
iPrim = colCand(1)
aiPrim(nPrim) = iPrim
colCand.Remove 1

' remove all multiples
For i = 2 To n \ iPrim
colCand.Remove CStr(i * iPrim)
Next i
Loop

'list 'em
Range("A1").Resize(nPrim).Value = WorksheetFunction.Transpose(aiPrim)
Beep
End Sub




the code is not mine , and allthough there are comments and i know it generate prime numbers , i dont understand the do while loop code , i dont understand what it does in each line , if anyone can read it and explain it in a simple manner .

and yes i'v tried running the code line by line to figure it out without success.

thanks in advance for your help guys .

Simon Lloyd
10-27-2017, 05:43 PM
' initialize candidates
For i = 2 To n
colCand.Add Item:=i, Key:=CStr(i)
Next i
Collects the number of prime number candidates

Do While colCand.Count
' first number in colCand is a prime
nPrim = nPrim + 1
iPrim = colCand(1)
aiPrim(nPrim) = iPrim
colCand.Remove 1

' remove all multiples
For i = 2 To n \ iPrim
colCand.Remove CStr(i * iPrim)
Next i
Loop
DoWhile keeps running the code below for each iteration, the iterations are set by the collection of candidate numbers.
Loop simply sends it back to DoWhile until colCand count has been exhausted.

wannabe11
10-28-2017, 05:55 AM
' initialize candidates
For i = 2 To n
colCand.Add Item:=i, Key:=CStr(i)
Next i
Collects the number of prime number candidates

Do While colCand.Count
' first number in colCand is a prime
nPrim = nPrim + 1
iPrim = colCand(1)
aiPrim(nPrim) = iPrim
colCand.Remove 1

' remove all multiples
For i = 2 To n \ iPrim
colCand.Remove CStr(i * iPrim)
Next i
Loop
DoWhile keeps running the code below for each iteration, the iterations are set by the collection of candidate numbers.
Loop simply sends it back to DoWhile until colCand count has been exhausted.

i dont know understand the part where the code detect the prime numbers and then seperate them .

Simon Lloyd
10-28-2017, 01:26 PM
Is this homework or an assignment?

SamT
10-28-2017, 05:26 PM
Do While... While expects a Boolean
A numerical 0 is a Boolean False, all other numbers are Boolean True

I like being specific when converting Variable Types...

Do While CBool(colCand.Count)