Results 1 to 15 of 15

Thread: Prime number generator

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2012
    Posts
    3

    Question Prime number generator

    Hi,

    My problem is that i need to generate the first 25 prime numbers and output them, i have seen various bits of code using the "mod" operator but im not sure how this works
    no input should be required for this program it just needs to identify a prime number and display the first 25

    although this is my first time posting here any help would be appreciated.

    Thanks,

    Craig

  2. #2
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: Prime number generator

    You need to know:
    1. What's the definition of a prime number?
    2. What does the "mod" operator do?
    Once you have the answer, you can very much come up with an algorithm to determine if a number is prime or not. Once you have this algorithm, to get the 1st 25 prime numbers, you start out with a value and run a loop. For each loop iteration, you test if the value is a prime number (and if it is, add it to your list) then increment it by 1. You keep looping until your prime list has 25 numbers in it.
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  3. #3
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    993

    Re: Prime number generator

    what have you tried?
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  4. #4

    Thread Starter
    New Member
    Join Date
    Sep 2012
    Posts
    3

    Re: Prime number generator

    I have been trying to workout how to identify a prime number in vb so that i can store them in an array and later output them

  5. #5
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Prime number generator

    Mod is short for modulo ... the result is the remainder value of the division operation .... 4 mod 2 is 0 because 4 divided by 2 is 2, no remainder. 5 mod 2 is 1 (5/2 = 2R1).... 7 mod 2 is 1.

    As for primes....
    First, it can never be an even number... so if the number mod 2 is 0 then it's not a prime (that's why I used 2 in the examples above). 1 is a given, so is 3. So that's where I'd start at...1.... then add 2 each time. After adding 2 to the current number, see if it is divisible by any of the previous primes evenly .. if the mod of any of the primes is 0, then that number is divisible evenly by that number and therefore not a prime.

    Now, simply create an array with an upper bound of 25... use one counter to keep track of the index in the array... and loop until you reach 25 on the index.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  6. #6
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Prime number generator

    Here is an implementation of the Sieve of Eratosthenes I did years ago in VB6. I adapted it to VB.Net:-
    vbnet Code:
    1. Public Class PrimeGenerator
    2.  
    3.     Private Class DeselectableNumber
    4.         Public Value As Integer
    5.         Public bStruckOut As Boolean
    6.     End Class
    7.  
    8.     Public Shared Function GetPrimes(ByVal max As Integer) As Integer()
    9.         Return FindPrimes(CreateNumberList(max))
    10.     End Function
    11.  
    12.     Private Shared Function CreateNumberList(ByVal MaxNumber As Integer) As DeselectableNumber()
    13.         'Create an array of type DeselectableNumber. One entry for
    14.         'every number between 0 to MaxNumber
    15.         Return Enumerable.Range(0, MaxNumber + 1).Select(Of DeselectableNumber)(Function(n) New DeselectableNumber With {.Value = n, .bStruckOut = False}).ToArray
    16.     End Function
    17.  
    18.     Private Shared Function FindPrimes(ByVal NumList As IList(Of DeselectableNumber)) As Integer()
    19.  
    20.         Dim lLastPrime As Integer
    21.         Dim i As Integer
    22.         Dim lStruckCount As Integer
    23.         Dim bRemainArePrime As Boolean 'Reached a point where all remaining numbers are prime
    24.  
    25.         Dim lstPrimes As New List(Of Integer)
    26.  
    27.         lLastPrime = 2
    28.  
    29.         Do Until (lStruckCount >= NumList.Count - 1 Or bRemainArePrime = True)
    30.  
    31.             For i = lLastPrime To NumList.Count - 1
    32.                 With NumList.Item(i)
    33.  
    34.                     If .Value Mod lLastPrime = 0 And .bStruckOut = False Then
    35.  
    36.                         .bStruckOut = True
    37.                         lStruckCount = lStruckCount + 1
    38.  
    39.                         If .Value = lLastPrime Then
    40.                             lstPrimes.Add(lLastPrime)
    41.                         End If
    42.                     End If
    43.  
    44.                 End With
    45.  
    46.             Next
    47.  
    48.             For i = lLastPrime To NumList.Count - 1
    49.                 If NumList.Item(i).bStruckOut = False Then lLastPrime = NumList.Item(i).Value : Exit For
    50.             Next
    51.  
    52.             'If the next multiple of the next prime number is greater than
    53.             'our upper limit then all the remaining numbers that were
    54.             'not struck our are prime numbers
    55.             If lLastPrime * 2 > NumList.Count - 1 Then
    56.                 bRemainArePrime = True
    57.             End If
    58.  
    59.         Loop
    60.  
    61.         'All remaining unstruck numbers are prime
    62.         If bRemainArePrime Then
    63.             For i = 2 To NumList.Count - 1
    64.                 With NumList(i)
    65.                     If .bStruckOut = False Then lstPrimes.Add(.Value)
    66.                 End With
    67.             Next
    68.  
    69.         End If
    70.  
    71.         FindPrimes = lstPrimes.ToArray
    72.  
    73.     End Function
    74.  
    75.  
    76. End Class

    Open a new Windows Forms project and place a ListBox on Form1 and place this code in Form1_Load:-
    vbnet Code:
    1. '
    2.         Dim primes = PrimeGenerator.GetPrimes(100)
    3.         ListBox1.DataSource = primes

    Execute the program and the ListBox would contain a list of primes between 0 and 100.
    Last edited by Niya; Sep 5th, 2012 at 08:30 PM. Reason: Optimized Algorithm
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  7. #7
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Prime number generator

    I would be tempted to point you at the first three articles from the Craftsman series, where a "naive" Sieve of Eratosthenes implementation is refactored into something clearer:
    http://objectmentor.com/resources/ar...craftsman1.pdf
    http://objectmentor.com/resources/ar...craftsman2.pdf
    http://objectmentor.com/resources/ar...craftsman3.pdf

    (In fact, I'd be tempted to point everyone to the entire series, but there's no URL pointing directly to the series by itself, you need to go to http://objectmentor.com/resources/pu...dArticles.html and then click the Craftsman link under "By Topic" which loads the articles in the same page.)

    However, the classic Sieve algorithm gets you "the primes in the first n numbers" rather than "the first n primes". I can imagine a slight tweak to the algorithm that would give you that but I'm not sure it's 100% correct. Essentially, I would imagine that you could keep a list of primes plus a multiple of that prime. As you increment the candidate prime, check whether any of the multiples of the prime are equal to the current candidate. If they are, the number is not a prime. Also check whether any of the multiples are less than the prime, if so you add the prime to the multiple again to get the next multiple. This should always be greater than the current candidate.

    This approach should be quicker than checking the modulo of the candidate prime because it avoids any division operations, and also only bothers to check for prime factors of the candidate. It looks correct to my brief analysis, but you'd probably want to run a few tests to check.

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,416

    Re: Prime number generator

    Quote Originally Posted by techgnome View Post
    As for primes....
    First, it can never be an even number...
    2 is a prime number...

    here's my Prime Number Finder:

    Name:  06-09-2012 18.14.58.jpg
Views: 7721
Size:  22.9 KB

    vb.net Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    4.         Dim seed As Integer, count As Integer
    5.         If Integer.TryParse(TextBox1.Text, seed) AndAlso seed > 0 AndAlso Integer.TryParse(TextBox2.Text, count) Then
    6.             ListBox1.Items.Clear()
    7.             Dim startAt As Integer = seed - 1
    8.             For n As Integer = 1 To count
    9.                 startAt = getNextPrime(startAt)
    10.                 ListBox1.Items.Add(startAt)
    11.             Next
    12.         End If
    13.     End Sub
    14.  
    15.     ''' <summary>
    16.     ''' isPrime
    17.     ''' </summary>
    18.     ''' <param name="x"></param>
    19.     ''' <returns></returns>
    20.     ''' <remarks>a Prime Number is a number greater than 1 which is divisible only by itself and 1</remarks>
    21.     Private Function isPrime(ByVal x As Integer) As Boolean
    22.         If x < 2 Then Return False
    23.         Return Enumerable.Range(2, x - 2).All(Function(n) x Mod n <> 0)
    24.     End Function
    25.  
    26.     Private Function getNextPrime(ByVal x As Integer) As Integer
    27.         Dim startAt As Integer = x + 1
    28.  
    29.         Do
    30.             If isPrime(startAt) Then
    31.                 Return startAt
    32.             Else
    33.                 startAt += 1
    34.             End If
    35.         Loop
    36.     End Function
    37.  
    38.     Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    39.         For c As Integer = 0 To Me.Width Step 25
    40.             e.Graphics.DrawLine(Pens.LightGray, c, 0, c, Me.Height)
    41.         Next
    42.         For r As Integer = 0 To Me.Height Step 25
    43.             e.Graphics.DrawLine(Pens.LightGray, 0, r, Me.Width, r)
    44.         Next
    45.     End Sub
    46.  
    47. End Class

  9. #9
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Prime number generator

    Quote Originally Posted by Evil_Giraffe View Post
    Essentially, I would imagine that you could keep a list of primes plus a multiple of that prime. As you increment the candidate prime, check whether any of the multiples of the prime are equal to the current candidate. If they are, the number is not a prime. Also check whether any of the multiples are less than the prime, if so you add the prime to the multiple again to get the next multiple. This should always be greater than the current candidate.

    This approach should be quicker than checking the modulo of the candidate prime because it avoids any division operations, and also only bothers to check for prime factors of the candidate. It looks correct to my brief analysis, but you'd probably want to run a few tests to check.
    Interesting, off the top of your head, just how much of an improved performance would you expect ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  10. #10
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Prime number generator

    Quote Originally Posted by Niya View Post
    Interesting, off the top of your head, just how much of an improved performance would you expect ?
    For finding the first 25? Microseconds.

    For the more general case, I'd guess at orders of magnitude, but that is a complete guess. Even if you restrict the modulo algorithm just to trying the primes you've found already, that's still one module operation (expensive) and a comparison with zero for each prime smaller than your candidate. For the algorithm I posited (and remember that I've not done anything particularly rigorous to prove it works) then you have an equality comparison, a less than comparison and potentially (1 in every p iterations for prime p) an addition operation (very cheap) for each prime smaller than the candidate.

    The proof of the pudding is always in the actual performance, however. The best way to get a sense of how much improved performance you'll get is to code both approaches and time them.

  11. #11
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Prime number generator

    My initial thought went to a loop and returning a prime number whenever it was found. In C# I would use the yield keyword which vb.net doesn't have in all but the newest frameworks. To get around this you can create a class that inherits from IEnumerable(Of T) and IEnumerator(Of T).

    vb.net Code:
    1. Public MustInherit Class Yielder(Of T)
    2.     Implements IEnumerable(Of T)
    3.     Implements IEnumerator(Of T)
    4.  
    5.     Private _current As T
    6.  
    7.     Public Sub New()
    8.     End Sub
    9.  
    10.     Protected MustOverride Function [Yield]() As T
    11.  
    12.     Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
    13.         Return Me
    14.     End Function
    15.  
    16.     Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
    17.         Return Me
    18.     End Function
    19.  
    20.     Public ReadOnly Property Current As T Implements System.Collections.Generic.IEnumerator(Of T).Current
    21.         Get
    22.             Return _current
    23.         End Get
    24.     End Property
    25.  
    26.     Public ReadOnly Property Current1 As Object Implements System.Collections.IEnumerator.Current
    27.         Get
    28.             Return _current
    29.         End Get
    30.     End Property
    31.  
    32.     Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
    33.         _current = [Yield]()
    34.         Return True
    35.     End Function
    36.  
    37.     Public Sub Reset() Implements System.Collections.IEnumerator.Reset
    38.         Throw New NotImplementedException()
    39.     End Sub
    40.  
    41. #Region "IDisposable Support"
    42.     Private disposedValue As Boolean = False
    43.  
    44.     Protected Overridable Sub Dispose(disposing As Boolean)
    45.         If Not Me.disposedValue Then
    46.             If disposing Then
    47.                 ' TODO: dispose managed state (managed objects).
    48.             End If
    49.  
    50.             ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
    51.             ' TODO: set large fields to null.
    52.         End If
    53.         Me.disposedValue = True
    54.     End Sub
    55.  
    56.     Public Sub Dispose() Implements IDisposable.Dispose
    57.         Dispose(True)
    58.         GC.SuppressFinalize(Me)
    59.     End Sub
    60. #End Region
    61.  
    62. End Class

    Next I needed a class that will start calculating prime numbers and spit them out as they're found.

    vb.net Code:
    1. Public Class Primes
    2.     Inherits Yielder(Of Long)
    3.  
    4.     Dim primes As New List(Of Long)
    5.     Dim candidate = 1
    6.  
    7.     Protected Overrides Function [Yield]() As Long
    8.         Do While candidate <= Long.MaxValue
    9.             candidate += 1
    10.             If candidate = 2 Then
    11.                 primes.Add(candidate)
    12.                 Return candidate
    13.             End If
    14.             Dim IsPrime = Function(n) primes.TakeWhile(Function(p) p <= Math.Sqrt(n)).FirstOrDefault(Function(p) n Mod p = 0) = 0
    15.             If IsPrime(candidate) Then
    16.                 primes.Add(candidate)
    17.                 Return candidate
    18.             End If
    19.         Loop
    20.         Return Nothing
    21.     End Function
    22. End Class

    Here are a couple of examples using the Primes class.

    vb.net Code:
    1. Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    2.         Dim first25Primes = New Primes().Take(25).ToList()
    3.         Dim maxValue = 1000
    4.         Dim primesUnder1000 = New Primes().TakeWhile(Function(p) p <= maxValue).ToList()
    5.         Dim maxPrimeUnder1000 = New Primes().TakeWhile(Function(p) p <= maxValue).Max()
    6.     End Sub
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  12. #12

    Thread Starter
    New Member
    Join Date
    Sep 2012
    Posts
    3

    Thumbs up Re: Prime number generator

    Thanks for everyone's help but i figured out the simplest way do do this

    Code:
    Public Class frmMain
    
        Const Required_No_Primes = 25
    
        Dim primes_Found As Integer = 0
        Dim CurrentNumber As Integer = 0
        Dim is_Prime As Boolean = False
    
        Private Sub btnRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click
    
            Do
    
                CurrentNumber += 1
    
                If CurrentNumber = 1 Then
                    is_Prime = False
                ElseIf CurrentNumber = 2 Or CurrentNumber = 3 Then
                    is_Prime = True
                Else
                    For counter As Integer = 2 To (CurrentNumber - 1)
                        If CurrentNumber Mod counter = 0 Then
                            is_Prime = False
                            Exit For
                        Else
                            is_Prime = True
                        End If
                    Next
                End If
    
                If is_Prime = True Then
                    lstOutput.Items.Add(CurrentNumber)
                    primes_Found += 1
                End If
    
            Loop Until primes_Found = Required_No_Primes
    
        End Sub
    
    End Class

  13. #13
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Prime number generator

    Quote Originally Posted by xerox3333 View Post
    Thanks for everyone's help but i figured out the simplest way do do this
    Actually, given your requirements, no you didn't. Let's recap:

    Quote Originally Posted by xerox3333 View Post
    My problem is that i need to generate the first 25 prime numbers and output them
    [...]
    no input should be required for this program it just needs to identify a prime number and display the first 25
    "Identifying a prime number" isn't actually a requirement. It's an implementation detail disguised as a requirement. Thus, a professional programmer would need to clarify whether there was a hidden requirement behind this and if not then they are free to ignore it. Which I will preceed to do (since the only hidden requirement would be to have a variable number of primes priduced which is explicitly ruled out. So that leaves us with the only requirement (bolded) being to display the first 25 primes. Which seems to me your solution is more complicated than this:

    vbnet Code:
    1. Public Class Form1
    2.  
    3.     Private Sub btnRun_Click(sender As System.Object, e As System.EventArgs) Handles btnRun.Click
    4.  
    5.         Dim primes() As Integer = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
    6.  
    7.         For Each prime In primes
    8.             lstOutput.Items.Add(prime)
    9.         Next
    10.  
    11.     End Sub
    12.  
    13. End Class

    No, I'm not being (totally) facetious. The point being that for the current requirements, do you actually need to identify primes? No, you don't. Hard coding the list is far quicker than writing the prime algorithm, so you get your software to a finished state sooner and can get it into customers' hands generating revenue earlier.

    In the future you might find that the number of primes it is required to generate increases. At this stage, it might be simpler to increase the number of hardcoded primes, or it might make sense to implement the algorithm then to allow for fa more primes than you could hard code reliably. That is a decision you can take then. Of course, such real world concerns would be very unlikely to impress a programming course instructor.

  14. #14
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Prime number generator

    There is also a middle of the road solution....you can use prime generating code to generate the code itself. You just need to generate a string enclose in curly braces with each number separated by commas and embed that to initialize your array. A simple look-up will always outperform any algorithm to generate primes.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  15. #15
    PowerPoster SJWhiteley's Avatar
    Join Date
    Feb 2009
    Location
    South of the Mason-Dixon Line
    Posts
    2,256

    Re: Prime number generator

    Quote Originally Posted by Evil_Giraffe View Post

    No, I'm not being (totally) facetious. The point being that for the current requirements, do you actually need to identify primes? No, you don't. Hard coding the list is far quicker than writing the prime algorithm, so you get your software to a finished state sooner and can get it into customers' hands generating revenue earlier.

    In the future you might find that the number of primes it is required to generate increases. At this stage, it might be simpler to increase the number of hardcoded primes, or it might make sense to implement the algorithm then to allow for fa more primes than you could hard code reliably. That is a decision you can take then. Of course, such real world concerns would be very unlikely to impress a programming course instructor.
    A very good point, and will be relevant over the next few weeks/months as screwl is back in session.

    Also, you demonstrate a flaw with going to the forums for help - your code generates the required primes but would score few points in the non-real world
    "Ok, my response to that is pending a Google search" - Bucky Katt.
    "There are two types of people in the world: Those who can extrapolate from incomplete data sets." - Unk.
    "Before you can 'think outside the box' you need to understand where the box is."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width