vba 判断一个数是否为素数的代码
PrivateSub查找回文素数_Click()DimiAsInteger,jAsInteger,kAsInteger'声明变量i,j,k为整型DimMyvalueAsS...
Private Sub 查找回文素数_Click()
Dim i As Integer, j As Integer, k As Integer
'声明变量 i ,j ,k 为整型
Dim Myvalue As String
'声明字符类型变量 Myvalue
message = "请输入一个100以下的两位正整数"
title = "请输入边界值"
Myvalue = InputBox(message, title, 1): Rem 获取用户输入的值
Do While renum(Len(Myvalue)) = False
Myvalue = InputBox(message, title, 1)
Loop '本循环体用于等待用户输入有效边界值
For i = CInt(Myvalue) To 10 Step -1
title = "规定范围的最大回文素数"
If prim(i) Then
j = i
k = 0
Do While j > 0
k = k * 10 + j Mod 10
j = j \ 10
Loop
If prim(k) Then
MsgBox "你输入的值范围内最大的回文素数是" & Chr(10) & i, vbOKOnly, title
Exit Sub
End If
End If
Next i
If i = 9 Then
MsgBox "没有小于你输入数值的回文素数", vbOKOnly, title
End If
End Sub
Public Function renum(n As Integer) As Boolean
If n = 2 Then
renum = True
Else
renum = False
MsgBox "需要输入的是100以下的两位正整数,输入不符合规定请重新输入"
End If
End Function
Public Function prim(n As Integer) As Boolean
End Function
prim里面判断是否素数该怎么写,若是素数返回true,不是返回false 展开
Dim i As Integer, j As Integer, k As Integer
'声明变量 i ,j ,k 为整型
Dim Myvalue As String
'声明字符类型变量 Myvalue
message = "请输入一个100以下的两位正整数"
title = "请输入边界值"
Myvalue = InputBox(message, title, 1): Rem 获取用户输入的值
Do While renum(Len(Myvalue)) = False
Myvalue = InputBox(message, title, 1)
Loop '本循环体用于等待用户输入有效边界值
For i = CInt(Myvalue) To 10 Step -1
title = "规定范围的最大回文素数"
If prim(i) Then
j = i
k = 0
Do While j > 0
k = k * 10 + j Mod 10
j = j \ 10
Loop
If prim(k) Then
MsgBox "你输入的值范围内最大的回文素数是" & Chr(10) & i, vbOKOnly, title
Exit Sub
End If
End If
Next i
If i = 9 Then
MsgBox "没有小于你输入数值的回文素数", vbOKOnly, title
End If
End Sub
Public Function renum(n As Integer) As Boolean
If n = 2 Then
renum = True
Else
renum = False
MsgBox "需要输入的是100以下的两位正整数,输入不符合规定请重新输入"
End If
End Function
Public Function prim(n As Integer) As Boolean
End Function
prim里面判断是否素数该怎么写,若是素数返回true,不是返回false 展开
展开全部
写法有多种,以下代码可行,供参考:
Public Function prim(n As Integer) As Boolean
Dim i&, j%, bo As Boolean
For i = 3 To n / 2
If n Mod i = 0 Then bo = True: Exit For
Next
If n = 2 Or bo = False And n > 1 And n Mod 2 = 1 Then prim = True
End Function
追问
大神能不能帮我这下注释😂😂😂
追答
For i = 3 To n / 2 Step 2 '按3,5,7,9……奇数循环至这个数的一半
If n Mod i = 0 Then bo = True: Exit For '如果能除尽bo为真说明不是素数,并退出循环
Next
If n = 2 Or bo = False And n > 1 And n Mod 2 = 1 Then prim = True '素数判断(因为函数值默认为False,所以只对素数赋值为真即可)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询