Private Declare Function GetTickCount Lib "kernel32" () As Long
Private Sub Command1_Click()
Dim a(200000) As Long
Dim tt As Long
Dim n As Long
Dim k As Long
Dim i As Long
Dim j As Long
Dim a1 As Long
Dim a2 As Long
Dim k1 As Long
Dim l As Long
aa = 1 - Check1.Value
tt = GetTickCount()
a(0) = 2
a(1) = 3
a1 = 4
k = 1
k1 = 1
For n = 2 To 1600
a2 = a1 + n + n + 1
If n > a(k) Then k = k + 1
l = n Mod 2
For i = a1 + 1 + l To a2 - 2 + l Step 2
For j = 1 To k
If i Mod a(j) = 0 Or i = 1 Then Exit For '去掉Or i = 1更慢?
If j = k Then
k1 = k1 + 1
a(k1) = i
End If
Next
Next
a1 = a2
Next
If aa = 1 Then
Cls
Print "第" & k1 + 1 & "个素数为"; a(k1)
MsgBox (GetTickCount() - tt) & "毫秒"
Else
Open "li.txt" For Output As #1
For i = 0 To k1
Print #1, "第" & i + 1 & "个素数为"; Tab(20); a(i)
Next
MsgBox (GetTickCount() - tt) & "毫秒"
Close
End If
Erase a()
End Sub
Dim prime(max) As Long
Dim i As Long
Dim tt As Long
For i = 0 To max
prime(i) = 1
Next
Dim current As Long
Dim dCurrent As Long
Dim temp As Long
tt = GetTickCount
current = 3
While current <= max
If prime(current) = 1 Then
dCurrent = current * 2
temp = current + dCurrent
While temp < max
prime(temp) = 0
temp = temp + dCurrent
Wend
End If
current = current + 2
Wend
Dim primeNum As Long
primeNum = 1
For i = 3 To max Step 2
If prime(i) = 1 Then primeNum = primeNum + 1
Next i
MsgBox "PrimeNum:" + Str(primeNum) + " Time:" + Str(GetTickCount - tt)
End Sub
计算到1001989,使用时间120ms。
还有一个对3不进行计算的代码:
Private Sub Command2_Click()
Const max = 2600000
Dim prime(max) As Long
Dim i As Long
Dim tt As Long
For i = 0 To max
prime(i) = 1
Next
Dim current As Long
Dim dCurrent As Long
Dim temp As Long
tt = GetTickCount
current = 1
While current <= max - 6
current = current + 4
If prime(current) = 1 Then
dCurrent = current * 2
temp = current + dCurrent
While temp <= max
prime(temp) = 0
temp = temp + dCurrent
Wend
End If
current = current + 2
If prime(current) = 1 Then
dCurrent = current * 2
temp = current + dCurrent
While temp <= max
prime(temp) = 0
temp = temp + dCurrent
Wend
End If
Wend
Dim primeNum As Long
primeNum = 2
i = 1
While i <= max - 6
i = i + 4
If prime(i) = 1 Then primeNum = primeNum + 1
i = i + 2
If prime(i) = 1 Then primeNum = primeNum + 1
Wend
MsgBox "PrimeNum:" + Str(primeNum) + " Time:" + Str(GetTickCount - tt)
End Sub
int
WINAPI
WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
DWORD start = GetTickCount();
// begin
char * prime = new char [MAX_COUNT+1];
prime[2] = PRIME;
int n, m, s, q;
for( n = 4; n <= MAX_COUNT; n += 2 )
{
prime[n] = COMPOSITE;
}
// the next for loop is not always necessary
for( n = 3; n <= MAX_COUNT; n += 2 )
{
prime[n] = PRIME;
}
q = (int)sqrt((float)MAX_COUNT);
for( n = 3; n <= q; n += 2 )
{
if( prime[n] == PRIME )
{
for( m = n*n, s = n+n; m<= MAX_COUNT; m+= s )
{
prime[m] = COMPOSITE;
}
}
}
// end
DWORD end = GetTickCount();