|
楼主 |
发表于 2014-1-19 10:17
|
显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 aoe1981 于 2014-1-19 10:27 编辑
这次再行上传一个优化版1,主要做了两点:
1、进一步参照优化了循环次数,现在按2、3、5、7、9、11、13.........直到输入数据的开平方根(进一法取整)为止,并且在其中划掉3、5、7的倍数,当然,也可以判断划掉11、13、17、19、23........等的倍数,以更多的减少循环次数,但是这样做没完没了,代码重复冗长;
2、真正实现了对历史判断结果的无重复记录,前次所谓无重复其实有点问题,传一张记录结果图,会感受到这样做带来便于复制粘贴结果的好处:
以下是优化后的代码:
Private Sub CommandButton1_Click()
Dim x&, i&, n#, j#, pdjg$, d As Object, ys(), cs(), rng As Range, rng1 As Range '判断结果、因数、次数
If TextBox1.Text = "" Then MsgBox "请输入要判断的自然数!", , "友情提示": Label3.Caption = "": Exit Sub
If IsNumeric(TextBox1.Text) = False Then MsgBox "请输入数字,中间不能有空格!", , "友情提示": TextBox1.Text = "": Label3.Caption = "": Exit Sub
If TextBox1.Text <> Int(TextBox1.Text) Then MsgBox "请输入整数!", , "友情提示": TextBox1.Text = "": Label3.Caption = "": Exit Sub
If TextBox1.Text < 2 Then MsgBox "请输入大于1的自然数!", , "友情提示": TextBox1.Text = "": Label3.Caption = "": Exit Sub
If TextBox1.Text > 999999999999999# Then MsgBox "数据过大,本程序最大可判断的15位数!", , "友情提示": TextBox1.Text = "": Label3.Caption = "": Exit Sub
n = TextBox1.Text
Set d = CreateObject("Scripting.Dictionary")
Do
If n = 2 Then Exit Do
If n ^ 0.5 = Int(n ^ 0.5) Then x = n ^ 0.5 Else x = Int(n ^ 0.5 + 1)
For i = 1 To x Step 2
If i = 1 Then i = 2
If i <> 3 And i Mod 3 = 0 Then GoTo 100
If i <> 5 And i Mod 5 = 0 Then GoTo 100
If i <> 7 And i Mod 7 = 0 Then GoTo 100
j = n / i
If j = Int(j) Then d(i) = d(i) + 1: GoTo 200
100:
If i = 2 Then i = 1
Next
Exit Do
200:
n = j
Loop
If d.Count <> 0 Then d(n) = d(n) + 1
ys() = d.keys
cs() = d.items
For i = 0 To UBound(ys)
If cs(i) > 1 Then pdjg = pdjg & ys(i) & "^" & cs(i) & "×" Else pdjg = pdjg & ys(i) & "×"
Next i
If pdjg = "" Then Label3.Caption = "质数" Else Label3.Caption = "合数 " & Left(pdjg, Len(pdjg) - 1)
'以下代码往工作表中记录判断结果
If [g1] = "" Then Set rng = [g1] Else Set rng = Cells(Rows.Count, "g").End(xlUp).Offset(1, 0)
If Cells(1, 256) = "" Then Set rng1 = Cells(1, 256) Else Set rng1 = Cells(Rows.Count, 256).End(xlUp).Offset(1, 0)
If Columns(256).Find(TextBox1.Text, , , xlWhole) Is Nothing Then
If Label3.Caption <> "质数" Then
rng.Value = TextBox1.Text & "=" & Left(pdjg, Len(pdjg) - 1)
Else
rng.Value = TextBox1.Text & "是质数"
End If
rng1.Value = TextBox1.Text
End If
End Sub
缺陷:仍然只能最大判断15位数,稍后再行研究超过15位数的,如果可以忍受这个范围,目前还算完美吧。。。呵呵
质数判断(参照优化版1).rar
(16 KB, 下载次数: 12)
|
|