vb输入一个正整数,若该数不是一个素数,则找出一个大于它的最小素数

2024-11-22 06:22:50
推荐回答(4个)
回答(1):

创建一个名为Text1的文本框输入正整数,一个Command1的按钮用以开始计算,结果显示在Label1里
程序如下
Private Sub Command1_Click()
Dim NumIn As Long, Num As Long
NumIn = Val(Text1)
If Not IsPrime(NumIn) Then
Num = NumIn + NumIn Mod 2 + 1
While Not IsPrime(Num)
Num = Num + 2
Wend
End If
Label1 = Num
End Sub

Function IsPrime(n As Long) As Boolean
Dim i%
For i = 2 To Sqr(n)
If n Mod i = 0 Then
IsPrime = False
Exit Function
End If
Next
IsPrime = True
End Function

回答(2):

private sub command1_click()
dim n as Long
dim Nss as boolean
n=val(trim(text1.text))
if ss(n)=True then
text2.text="N=" & n & " 是素数"
else
do while Nss=True
n=n+1
Nss=ss(N)
loop
text1.text=n
text2.text="N=" & n & " 是素数"
endif
end sub
或者把这段代码放到Text1 的change事件里
Function ss(Tmp As Long) As Boolean '素数判断
ss = True
For i = 2 To Tmp / 2
If Tmp Mod i = 0 Then
ss = False
Exit Function
End If
Next
End Function

回答(3):

Private Sub form_click()
Dim n As Long
n = Val(InputBox("请输入一个整数"))
If sushu(n) = False Then
Do
n = n + 1
If sushu(n) = True Then Exit Do
Loop
MsgBox "该数不是素数,大于它的最小素数是:" & n
Else
MsgBox "它是素数"
End If
End Sub

Private Function sushu(n As long) As Boolean
Dim i As Long
For i = 2 To Sqr(n)
If n Mod i = 0 Then Exit For
Next i
If i > Sqr(n) Then
sushu = True
End If
End Function

回答(4):

上班