VB中如何判断是否为质数

See this post in : English Version or French Version

 Private Sub Command1_Click()
 r = InputBox(“请输入您要判断的数字”)
 For i = 2 To r
   If Val(r) Mod i = 0 And i <> Val(r) Then ‘这里给出了非质数的条件
    MsgBox (“此数为非质数”)
    Exit Sub
   End If
 Next i
 MsgBox (“此数为质数”)
End Sub


‘列出1到100中的质数与非质数
Private Sub Command2_Click()
 r = 100 ‘设定最大范围为100
 Me.Caption = 0 ‘把按钮2的显示名称设为0,为了之后显示总数
 Me.ForeColor = vbBlue ‘把按钮2的显示名称的字体颜色设为蓝色
 For j = 1 To r
   For i = 2 To j
     If Val(j) Mod i = 0 And i <> Val(j) Then
      Me.ForeColor = vbBlue ‘非质数为蓝色
      Exit For
     Else
      Me.ForeColor = vbRed ‘质数为红色
     End If
   Next i
  Print ” ” & Format(j, “000”);
  If Me.ForeColor = vbRed Then Me.Caption = Me.Caption + 1 ‘显示质数的总数
  If j Mod 10 = 0 Then Print
 Next j
End Sub

Leave a Reply

↑ Back to top