1、1VB 程序设计素数判断并统计(作者:草原飞狼 2014 年 5 月 25 日)声明:仅供学习与交流使用,高手请飘过,谢谢!所有代码都是个人亲自编写并调试成功。布局2运行界面(1)运行界面(2)源代码如下:Private Sub Command1_Click()Rem 判断素数并进行统计,固定范围 2-100Dim n, k As IntegerDim i As Integeri = 0 i 用于控制换行For n = 2 To 100Rem 以下是素数判断算法,认真理解For k = 2 To Int(Sqr(n)If n Mod k = 0 ThenExit For 退出 for 循环,减
2、少不必要的循环End IfNext k3If k Sqr(n) ThenForm1.Picture1.Print n; 如果是素数,则输出i = i + 1If i Mod 10 = 0 Then 控制输出,每行 10 个数据Form1.Picture1.Print 换行End IfEnd IfNext nEnd SubPrivate Sub Command2_Click()Rem 退出Dim int_msg As Integerint_msg = MsgBox(“单击“是” 退出程序,单击“否”程序将继续进行! “, vbYesNo + vbQuestion + vbDefaultButto
3、n1, “退出提示“)If int_msg = vbYes ThenUnload MeEnd IfEnd SubPrivate Sub Command3_Click()Rem 判断素数并进行统计,指定范围 n1-n2Dim n, k As IntegerDim i As Integer 行输出控制变量Dim n1, n2 As Integer n1,n2 是指定范围的最小值和最大值i = 0Rem 判断第一个数据是否合法n1 = Val(InputBox(“请输入第一个整数“, “输入数据一“, “2“)Do While n1 n2 Thentemp = n1n1 = n2n2 = tempE
4、nd If4For n = n1 To n2For k = 2 To Int(Sqr(n)If n Mod k = 0 ThenExit ForEnd IfNext kIf k Int(Sqr(n) ThenForm1.Picture1.Print n;i = i + 1If i Mod 10 = 0 Then 控制换行,每 10 个换行Form1.Picture1.PrintEnd IfEnd IfNext nEnd SubPrivate Sub Command4_Click()Rem 固定范围内素数求和Dim n, k, i As IntegerDim sum As Singlei = 0
5、sum = 0For n = 2 To 100For k = 2 To Int(Sqr(n)If n Mod k = 0 Then 注意理解: n mod k=0Exit ForEnd IfNext kIf k Int(Sqr(n) ThenForm1.Picture1.Print n;sum = sum + n 累加求和i = i + 1If i Mod 10 = 0 Then 控制换行,每 10 个换行Form1.Picture1.PrintEnd IfEnd IfNext nLabel1.Caption = “所有素数的和是: “ sum = sum + ni = i + 1If i Mod 10 = 0 Then 控制换行,每 10 个换行Form1.Picture1.PrintEnd IfEnd IfNext nLabel1.Caption = “所有素数的和是: “ & Str(sum)End SubPrivate Sub Command6_Click()Rem 清空Form1.Picture1.ClsEnd Sub6Private Sub Form_Load()Rem 初始化With Picture1.FontName = “宋体“.FontSize = 16.FontBold = True.ForeColor = vbRedEnd WithEnd Sub