小木虫如何赠送金币:用VB编写一段代码判断输入的数是否素数。

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/30 19:27:43

方法一:

一个数n是素数的条件:不能被2 ~ n-1整除
用For…….Next语句
Dim I as Integer,N As Integer
N=val(InputBox(""))
For I=2 to N-1
If N Mod I=0 Then Exit For '如果能被2 ~ N-1中任何一个数整除,则不是素数,跳出For循环
Next I
If I >= N Then'如果正常跳出For循环,则I跳出循环For后的值应该是N,所以满足这个条件
Print N & "是素数"
Else
Print N & "不是素数"
End If

方法二:(一般都是用这种方法)

一个数n是素数的条件:不能被2 ~ Sqr(n)整除,数学上可以证明
1、用For…….Next语句
Dim I as Integer,N As Integer
N=val(InputBox(""))
For I=2 to int(Sqr(N))
If N Mod I=0 Then Exit For
Next I
If I >int(Sqr(N)) Then
Print N & "是素数"
Else
Print N & "不是素数"
End If
6、 用While….Wend循环
Dim I As Integer, N As Integer
N = Val(InputBox(""))
I = 2
c = Int(Sqr(N))
Do While I <= c
If N Mod I = 0 Then Exit Do
I = I + 1 '在For以外的
Loop
If I > c Then
Print N & "是素数"
Else
Print N & "不是素数"
End If
e.g.:请输出3~100之间的所有素数。
只要在判断上述判断素数的方法外加一个For N=3 To 100………Next N,如使用方法二,如下:
For N = 3 To 100 '3~100
For I = 2 To Int(Sqr(N))
If N Mod I = 0 Then Exit For
Next I
If I > Int(Sqr(N)) Then
Print N & "是素数"
else
Print N & "不是素数"
End If
Next N '3~100
e.g.:判断100~200的所有偶数可以分解为两个素数之和。
Function nf(n As Integer) As Boolean '判断n是否为素数
Dim s As Boolean
Dim I As Integer
s = False
For I = 2 To Int(Sqr(n)) '如果能被2 ~Int(Sqr(n))中任何一个数整除,则不是素数,跳出For循环
If n Mod I = 0 Then
Exit For
End If
Next I
If I > Int(Sqr(n)) Then '如果正常跳出For循环,则I跳出循环For后的值应该是N,所以满足这个条件
s = True '当I是素数时s=true
End If
nf = s '当I是素数时, nf=true,否则 nf=false
End Function
Private Sub form_click()
Dim t As Boolean
Dim q As Boolean
Dim I As Integer
Dim j As Integer
Dim a As Integer
For I = 100 To 200 Step 2
For j = 2 To I / 2 'I一定可分解为一个大于它一半的数和小于它一半的数
t = nf(j) '调用Funtion(函数)nf,判断i是否是素数,把nf的值(true或flase)赋值给变量t
If t = True Then '如果t是true 就往下执行,否则就执行到 End if(2)后面的next j语句
q = nf(I - j) '调用Funtion(函数)nf,判断i-j是否是素数,把nf的值(true或flase)赋值给变量q
If q = True Then '如果q是true(说明i-j是素数) 就往下执行,否则就跳到 End if(1),继续执行j循环

Print j, I - j '当q是true和t是True同时满足时,说明I的确能分解为两个素数,就打出 j 和 I-j 的值
Exit For '跳出j循环,判断下一个偶数
End If '(1)
End If '(2)
Next j
Next I
End Sub

哇,好多代码,