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 .
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 .