vb~~1到100的素数的代码

如题所述

第1个回答  推荐于2016-04-25
给form加一个按钮,然后复制代码过去运行,1-100的素数会打印到窗体

结果:
=================================
1 2 3 5 7
11 13 17 19 23
29 31 37 41 43
47 53 59 61 67
71 73 79 83 89
97
=================================
代码:
==========================
Option Explicit

Private Sub Command1_Click()
Dim i As Integer, strPrime As String, index As Integer
For i = 1 To 100
If isPrime(i) Then
If strPrime = "" Then
strPrime = CStr(i)
ElseIf index Mod 5 = 0 Then
strPrime = strPrime & vbCrLf & CStr(i)
Else
strPrime = strPrime & vbTab & CStr(i)
End If
index = index + 1
End If
Next i
Print strPrime
End Sub

Private Function isPrime(ByVal n As Integer) As Boolean
If n = 1 Then
isPrime = True
ElseIf n > 1 Then
Dim flag As Boolean, i As Integer
flag = True
For i = 2 To n - 1
If n Mod i = 0 Then
flag = False
End If
Next i

If flag Then
isPrime = True
Else
isPrime = False
End If
End If
End Function
==============本回答被提问者采纳
第2个回答  2008-09-09
一下代码运行后点击窗体后计算
Private Sub Form_Click()
For c = 1 To 100
bz = False
If c / 2 = c \ 2 Then
bz = True
End If

For d = 3 To Int(Sqr(c)) Step 2
If c / d = c \ d Then
bz = True
d = c
End If
DoEvents
Next d
If bz = False Then
Print Str(c)
End If
Next c
End Sub

Private Sub Form_Load()
Me.Height = 10000
End Sub