今天上午到学校培训,老师让我们用QBasic写一个程序,可以算出2到10000的所有质数,我是这样写的
FOR n = 2 TO 10000
k = 1
FOR i = 2 TO n - 1
IF (n MOD i) = 0 THEN
k = 0
END IF
NEXT i
IF k = 1 THEN
PRINT n;
END IF
NEXT n
这算是最简单的求质数的算法了,在我的P42.5上大概用了2分钟
看我老师的
n = 10000
DIM arr(n)
FOR i = 2 TO SQR(n)
IF arr(i) = 0 THEN
FOR j = i * i TO n STEP i
arr(j) = 1
NEXT j
END IF
NEXT i
FOR k = 1 TO n
IF arr(k) = 0 THEN
PRINT k;
END IF
NEXT k
这个在学校P3 800MHz上瞬间算出
由此可以看出算法的重要性
#include <stdio.h>
int prime[20000];
void main() {
int tmp,i=2;
while ((tmp=i)<20000)
if ((!prime[i++]) && (printf("%8d",i-1)))
while ((tmp+i-1)<20000) prime[tmp+=i-1]=1;
}
Private Declare Function GetTickCount Lib "kernel32" () As Long
Private Sub Command1_Click()
Dim tt As Long
Dim n As Long
Dim k As Long
tt = GetTickCount()
For n = 2 To 10000
k = 1
For i = 2 To Sqr(n)
If (n Mod i) = 0 Then
k = 0
Exit For
End If
Next
If k = 1 Then
Print n;
End If
Next
MsgBox (GetTickCount() - tt) & "毫秒"
End Sub
Private Declare Function GetTickCount Lib "kernel32" () As Long
Private Sub Command1_Click()
Dim tt As Long
Dim n As Long
Dim k As Long
Dim i As Long
tt = GetTickCount()
For n = 2 To 10000
k = Sqr(n)
For i = 2 To k
If (n Mod i) = 0 Then
Exit For
End If
If Abs(i - k) < 1 Then
Print n;
End If
Next i
Next n
MsgBox (GetTickCount() - tt) & "毫秒"
End Sub