VB求素数算法

[日期:2021-04-07] 作者:信息技术 次浏览 [字体: ]
素数是一个大于2,且不能被1和本身以外的整数整除的整数。 
判别某数m是否为素数最简单的方法是:
对于m 从 i=2,3,…,m-1判别m能否被i整除,只要有一个能整除,m不是素数,否则m是素数。

Dim i As Integer ,n As Integer  
    n = InputBox("请输入一个整数")
    For i = 2 To n-1
        If n Mod i = 0 Then
             Exit For
        End If
    Next i
    If i = n Then
        Print n & "是素数"
    Else
        Print n & "不是素数"
    End If

2.列举2-100以内的所有素数?

Dim i As Integer, n As Integer
Dim z As Boolean
z = False
i = 2
n = InputBox("请输入一个整数")
    Do While i < n - 1
        If n Mod i = 0 Then
             z = True
        End If
   i = i + 1
   Loop
    If z Then
        Print n & "不是素数"
    Else
        Print n & "是素数"
    End If