VB:求100以内所有素数,输出到窗体上,每行输出5个

2024-11-22 04:09:43
推荐回答(1个)
回答(1):

Private Function check(i As Integer) As Boolean
For j = 2 To CInt(Sqr(i)) + 1 '从2循环到i的平方根
If i Mod j = 0 Then '如果i除以j的余数为0,说明i不是素数
check = False '返回false
Exit Function '退出本过程
End If
Next j
check = True '循环结束没有退出过程,说明i不能整除从2到i平方根的所有数,也就是说i是素数,返回true
End Function

Private Sub Command1_Click()
Dim k As Integer, n As Integer
For k = 1 To 100
If n Mod 5 = 0 Then Print
If check(k) Then
Print k;
n = n + 1
End If
Next
End Sub