Visual Basic:如何显示 1 和输入数字之间的质数

Visual Basic: How can i display the prime numbers between 1 and the inputted number

大家好,我正在尝试查找任何输入的质数。我希望它们位于列表框中,而输入位于文本框中。我想使用两个参数,但我不知道如何使用。这是我需要紧急帮助的代码。我不是最擅长 visual basic 的,我只需要一些指导。我的代码不工作,但当我按下显示时显示一个下拉框。

Public Class Form1
    Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click

        Dim prim As Integer
        Dim test As Integer
        Dim imPrime As Boolean = False
        prim = CInt(txtNum.Text)
        test = prim

        If prim = 1 Then
            imPrime = False
            MessageBox.Show("Enter a number greater than one please")
        Else
            Do While prim >= 2
                For i As Integer = 2 To prim
                    If prim Mod i = 0 Then
                        imPrime = False
                        Exit For
                    Else
                        imPrime = True
                        lstPrime.Items.Add(prim)
                    End If
                Next
            Loop
        End If
        If imPrime = True Then
            lstPrime.Items.Add(prim)
        End If

    End Sub
End Class

我认为 while 循环没有按您的预期工作。您需要两个循环,第一个循环计数到可能的素数,内部循环计数到外循环中的计数器。

您可以在任何地方找到示例...这里是 one implemented in C#,但由于您的问题专门针对列表框,我已将其翻译为 VB。

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        calculatePrimes()
    End Sub

    Private Sub calculatePrimes()

        Dim prim As Integer
        Dim count As Integer = 0

        prim = CInt(Me.TextBox1.Text)
        If prim < 3 Then
            MsgBox("Please enter a bigger number")
            Return
        End If

        Me.ListBox1.Items.Clear()

        For i As Integer = 1 To prim
            Dim isPrime As Boolean = True
            For j As Integer = 2 To i
                If (i Mod j <> 0) Then count = count + 1
            Next
            If count = (i - 2) Then Me.ListBox1.Items.Add(i)
            count = 0
        Next

    End Sub
End Class

(假设您有一个名为 TextBox1 的用于输入的文本框和一个名为 ListBox1 的用于显示的列表框)

这是我最快的 VBA 代码,用于生成两个数字之间的质数。

生成的质数放入剪贴板。您将需要打开 您的 ms office word 并键入 Ctrl+V 以查看所有生成的质数。

Sub generateprimenumbersbetween()
Dim starting_number As Long
Dim last_number As Long
Dim primenumbers As Variant
Dim a As Long
Dim b As Long
Dim c As Long
starting_number = 1 'input value here
last_number = 1000000 'input value here
primenumbers = ""
For a = starting_number To last_number
    c = Round(Sqr(a)) + 1
    For b = 2 To c
        If a = 1 Or (a Mod b = 0 And c <> b) Then
            Exit For
        Else
            If b = c Then
                primenumbers = primenumbers & " " & a
                Exit For
            End If
        End If
    Next b
Next a
Dim answer As DataObject
Set answer = New DataObject
answer.SetText primenumbers
answer.PutInClipboard
End Sub