回复 3楼 wmf2014
这样对合数是快的,如1999999999是合数,但对素数的确很慢,如1999999973是素数,很慢,没有计算时间感觉很慢!用我的分解程序就比较快,1999999999=31*64516129。
我的程序:
Private Function fenjieyinzi(sa As String) As String
Dim x, a, b, k As String
a = Val(sa)
x = 3
If a <= 1 Or a > Int(a) Then
If a = 1 Then
fenjieyinzi = "它既不是质数,也不是合数"
Else
MsgBox "error"
End If
Else
Do While a / 2 = Int(a / 2) And a >= 4
If b = 0 Then
fenjieyinzi = fenjieyinzi & "2"
b = 1
Else
fenjieyinzi = fenjieyinzi & "*2"
End If
a = a / 2
k = a
Loop
Do While a > 1
Do While x <= Sqr(a)
Do While a / x = Int(a / x) And a >= x * x
If b = 0 Then
fenjieyinzi = fenjieyinzi & x
b = 1
Else
fenjieyinzi = fenjieyinzi & "*" & x
End If
a = a / x
Loop
x = x + 2
Loop
k = a
a = 1
Loop
If b = 1 Then
fenjieyinzi = fenjieyinzi & "*" & k
Else
fenjieyinzi = "这是一个质数"
End If
End If
End Function
Private Sub Command1_Click()
Dim a As Long
a = Trim(Text1)
Text2 = fenjieyinzi(Trim(a))
End Sub
用你的方法的确也是快,试用你的法改变为如下程序:(运行结果:判断数:1999999973 是素数!)
Private Sub Command1_Click()
If CLng(Text1.Text) <= 2 Then
MsgBox "判断数必须是大于2 ,并且是整数!", 16, "错误提示!"
Exit Sub
End If
Dim XX As Long, I As Long, J As Long, AA As Boolean
AA = False
XX = CLng(Text1.Text)
If Right(XX, 1) Mod 2 = 0 Then
Text2.Text = "判断数:" & XX & " 不是素数!"
ElseIf XX = 3 Then
Text2.Text = "判断数:" & XX & " 是素数!"
ElseIf XX Mod 6 = 5 Then
For I = 5 To Sqr(XX) Step 2
If XX Mod I = 0 Then
AA = True
Exit For
End If
Next I
If AA = True Then
Text2.Text = "判断数:" & XX & " 不是素数!"
ElseIf AA = False Then
Text2.Text = "判断数:" & XX & " 是素数!"
End If
ElseIf XX Mod 6 = 1 Then
For I = 5 To Sqr(XX) Step 2
If XX Mod I = 0 Then
AA = True
Exit For
End If
Next I
If AA = True Then
Text2.Text = "判断数:" & XX & " 不是素数!"
ElseIf AA = False Then
Text2.Text = "判断数:" & XX & " 是素数!"
End If
Else
Text2.Text = "判断数:" & XX & " 不是素数!"
End If
End Sub
[此贴子已经被作者于2020-5-8 20:32编辑过]