简体   繁体   English

素数Visual Basic

[英]Prime Number Visual Basic

I have an assignment and it says: 我有一个作业,上面写着:

You have been provided a working program named Prime. 为您提供了一个名为Prime的工作程序。
It has one input which is a single integer. 它有一个输入,是一个整数。
When the “Find Prime Number” button is pushed, the nth prime number is identified. 按下“查找素数”按钮时,将识别第n个素数。

For example: 例如:

if 4 is entered and the button is clicked, the response is “The 4th prime number is 7” is displayed. 如果输入4并单击按钮,则显示为“第四个素数为7”。 And if 9 is entered, the response is “The 9th prime number is 23” is displayed. 如果输入9,则显示为“第9个质数为23”。

The program is 100% accurate, it correct locates the nth prime. 该程序是100%准确的,它可以正确定位第n个素数。
The problem comes in when you try to find larger prime number. 当您尝试查找较大的质数时,就会出现问题。

For example: 例如:

if 10000 is entered and the button is clicked, the response is “The 10000th prime number is 104729” is displayed. 如果输入10000并单击按钮,则会显示“第10000个素数是104729”。 This is the correct answer; 这是正确的答案; however, it took over 48 seconds on my i7 computer to find the solution. 但是,在我的i7计算机上花费了48秒以上的时间才能找到解决方案。 Imagine how long it would take to find the millionth prime number. 想象一下找到第百万个质数需要花费多长时间。 Your task is analyze the problem to find a more efficient solution that would make the program more useful. 您的任务是分析问题,以找到更有效的解决方案,使该程序更有用。 First you must understand how the code provided works. 首先,您必须了解所提供的代码如何工作。 There is an exercise at the end of this document. 本文档末尾有一个练习。 You will use it to run the code by hand. 您将使用它来手动运行代码。 Once you understand how it works, analyze the problem of finding a prime number to make the program operate more efficiently. 了解了它的工作原理后,请分析查找质数以使程序更有效地运行的问题。 The reason why the program is slow for large numbers is because I preform a lot of unnecessary calculations. 大量程序运行缓慢的原因是因为我执行了许多不必要的计算。 Not you must use your own code. 不是,您必须使用自己的代码。 You cannot use any prebuilt prime number routines, functions, or libraries; 您不能使用任何预建的质数例程,函数或库; doing so will result in a zero for the assignment. 这样做将导致分配为零。 Thinking about what really needs to be done is the way to solve this. 思考真正需要做的事情是解决此问题的方法。

He says that the best way is to use arrays, but I don't know how to use arrays to solve this problem. 他说最好的方法是使用数组,但是我不知道如何使用数组来解决这个问题。 He also says to keep division (mod) at a minimum as well as if statements. 他还说,要使除法(mod)和if语句最少。

Here is the code he provided for us: 这是他为我们提供的代码:

Option Strict On
Public Class Form1


Private Sub PositionBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PositionBox.TextChanged
    If IsNumeric(PositionBox.Text) Then
        If Decimal.Parse(PositionBox.Text) >= 1 Then
            FindPrimeBtn.Enabled = True
        Else
            FindPrimeBtn.Enabled = False
        End If
    Else
        FindPrimeBtn.Enabled = False
    End If
End Sub

Private Sub FindPrimeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindPrimeBtn.Click
    Dim FinalPosition As Long
    Dim FinalPrime, Even As Long
    Dim Number As Long = 2
    Dim CurrentPosition As Long = 1

    Dim elapsed As System.TimeSpan

    Dim sw As Stopwatch = New Stopwatch()

    sw.Start() 'starts the clock
    Dim IsPrime As Boolean

    FinalPosition = Long.Parse(PositionBox.Text)

    Even = CurrentPosition Mod 2
    While (CurrentPosition > 2 And Even <> 0)
        IsPrime = True
    End While

    While (CurrentPosition <= FinalPosition)
        IsPrime = True

        For x = 2 To Number - 1
            If Number Mod x = 0 Then
                IsPrime = False
            End If
        Next

        If IsPrime Then
            FinalPrime = Number
            CurrentPosition += 1
        End If
        Number += 1
    End While

    elapsed = sw.Elapsed() 'captures the elapsed time it took to compute the result

    ResultLbl.Text = "The " + FinalPosition.ToString() + "th is " + FinalPrime.ToString()
    ElapsedTimeLbl.Text = "Elapsed time is " + elapsed.ToString()

End Sub
End Class

check out this article , specifically, where it says: effort can be reduced by selecting only prime numbers as candidate factors. 请查看这篇文章 ,特别是其中的内容: 仅选择素数作为候选因子可以减少工作量。 Furthermore, the trial factors need go no further than \\scriptstyle\\sqrt{n} because, if n is divisible by some number p, then n = p × q and if q were smaller than p, n would have earlier been detected as being divisible by q or a prime factor of q. 此外,试算因素的必要性不过是\\ scriptstyle \\ sqrt {n},因为如果n可被某个数p整除,则n = p×q,如果q小于p,则n会更早地被检测为可被q或质数q整除。

I think he wants you to store the primes you find in an array and then iterate through the set of primes in the array instead of iterating through each or each odd number. 我认为他希望您将找到的素数存储在数组中,然后遍历数组中的素数集,而不是遍历每个或每个奇数。

Not sure if he'll allow you to import system.math, where the square root function is, but that speeds it up. 不知道他是否允许您导入system.math,即平方根函数所在的位置,但这可以加快速度。 I suppose you could ask... 我想你可以问...

Anyways, I'm not using the stored array of found prime numbers, and didn't like all his variable names, but if it helps, I was working with this: 无论如何,我没有使用找到的质数的存储数组,也不喜欢他的所有变量名,但是如果有帮助,我可以使用此方法:

Option Strict On
Imports System.Math

Public Class Form1
    Private Sub PositionBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PositionBox.TextChanged
        If IsNumeric(PositionBox.Text) Then
            If Decimal.Parse(PositionBox.Text) >= 1 Then
                FindPrimeBtn.Enabled = True
            Else
                FindPrimeBtn.Enabled = False
            End If
        Else
            FindPrimeBtn.Enabled = False
        End If
    End Sub

    Private Sub FindPrimeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindPrimeBtn.Click
        Dim CurrentprimeSequence As Long = 1
        Dim FinalprimeSequence As Long
        Dim prime_possible As Double = 2
        Dim foundPrime As Double
        Dim test_div As Double
        'Dim Even As Long

        Dim elapsed As System.TimeSpan

        Dim sw As Stopwatch = New Stopwatch()

        sw.Start() 'starts the clock
        Dim IsPrime As Boolean

        FinalprimeSequence = Long.Parse(PositionBox.Text)

        'Even = CurrentprimeSequence Mod 2
        'While (CurrentprimeSequence > 2 And Even <> 0)
        '   IsPrime = True
        'End While
        FindPrimeBtn.Enabled = False

        While (CurrentprimeSequence <= FinalprimeSequence)
            IsPrime = True   ' until proven false

            test_div = 2
            Do While IsPrime And (test_div <= Sqrt(prime_possible))
                IsPrime = (prime_possible Mod test_div > 0)
                test_div = test_div + 1 - CDbl(test_div > 2)       ' skip odd numbers after 2
                'If test_div = 2 Then
                '   test_div = test_div + 1
                'Else
                '   test_div = test_div + 2
                'End If
            Loop

            'For test_div = 2 To Sqrt(prime_possible)         ' test if divisible by any number two to square root of candidate, skip even #s
            '   If prime_possible Mod test_div = 0 Then
            '       IsPrime = False
            '       Exit For       ' or change to while isprime and (test_div < prime_possible)
            '   End If
            'Next

            If IsPrime Then
                foundPrime = prime_possible
                If CurrentprimeSequence Mod 100000 = 0 Then
                    Debug.Print(CStr(CurrentprimeSequence) + " " + CStr(foundPrime) + " " + sw.Elapsed().ToString)
                End If
                CurrentprimeSequence += 1
            End If
            prime_possible += 1
        End While

        elapsed = sw.Elapsed() 'captures the elapsed time it took to compute the result

        ResultLbl.Text = "The " + FinalprimeSequence.ToString() + "th is " + foundPrime.ToString()
        ElapsedTimeLbl.Text = "Elapsed time is " + elapsed.ToString()
        FindPrimeBtn.Enabled = True
    End Sub
End Class

on my PC, it found the millionth prime in about 28 seconds, but you can't really compare performance across machines. 在我的PC上,它在大约28秒内发现了百万分之一的质数,但是您无法真正比​​较所有机器的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM