|
-
Sep 5th, 2012, 03:37 PM
#1
Thread Starter
New Member
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
-
Sep 5th, 2012, 03:50 PM
#2
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 -
-
Sep 5th, 2012, 04:05 PM
#3
Fanatic Member
Re: Prime number generator
-
Sep 5th, 2012, 04:52 PM
#4
Thread Starter
New Member
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
-
Sep 5th, 2012, 05:23 PM
#5
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
-
Sep 5th, 2012, 08:17 PM
#6
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:
Public Class PrimeGenerator
Private Class DeselectableNumber
Public Value As Integer
Public bStruckOut As Boolean
End Class
Public Shared Function GetPrimes(ByVal max As Integer) As Integer()
Return FindPrimes(CreateNumberList(max))
End Function
Private Shared Function CreateNumberList(ByVal MaxNumber As Integer) As DeselectableNumber()
'Create an array of type DeselectableNumber. One entry for
'every number between 0 to MaxNumber
Return Enumerable.Range(0, MaxNumber + 1).Select(Of DeselectableNumber)(Function(n) New DeselectableNumber With {.Value = n, .bStruckOut = False}).ToArray
End Function
Private Shared Function FindPrimes(ByVal NumList As IList(Of DeselectableNumber)) As Integer()
Dim lLastPrime As Integer
Dim i As Integer
Dim lStruckCount As Integer
Dim bRemainArePrime As Boolean 'Reached a point where all remaining numbers are prime
Dim lstPrimes As New List(Of Integer)
lLastPrime = 2
Do Until (lStruckCount >= NumList.Count - 1 Or bRemainArePrime = True)
For i = lLastPrime To NumList.Count - 1
With NumList.Item(i)
If .Value Mod lLastPrime = 0 And .bStruckOut = False Then
.bStruckOut = True
lStruckCount = lStruckCount + 1
If .Value = lLastPrime Then
lstPrimes.Add(lLastPrime)
End If
End If
End With
Next
For i = lLastPrime To NumList.Count - 1
If NumList.Item(i).bStruckOut = False Then lLastPrime = NumList.Item(i).Value : Exit For
Next
'If the next multiple of the next prime number is greater than
'our upper limit then all the remaining numbers that were
'not struck our are prime numbers
If lLastPrime * 2 > NumList.Count - 1 Then
bRemainArePrime = True
End If
Loop
'All remaining unstruck numbers are prime
If bRemainArePrime Then
For i = 2 To NumList.Count - 1
With NumList(i)
If .bStruckOut = False Then lstPrimes.Add(.Value)
End With
Next
End If
FindPrimes = lstPrimes.ToArray
End Function
End Class
Open a new Windows Forms project and place a ListBox on Form1 and place this code in Form1_Load:-
vbnet Code:
'
Dim primes = PrimeGenerator.GetPrimes(100)
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
-
Sep 6th, 2012, 04:02 AM
#7
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.
-
Sep 6th, 2012, 12:17 PM
#8
Re: Prime number generator
 Originally Posted by techgnome
As for primes....
First, it can never be an even number...
2 is a prime number...
here's my Prime Number Finder:

vb.net Code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim seed As Integer, count As Integer
If Integer.TryParse(TextBox1.Text, seed) AndAlso seed > 0 AndAlso Integer.TryParse(TextBox2.Text, count) Then
ListBox1.Items.Clear()
Dim startAt As Integer = seed - 1
For n As Integer = 1 To count
startAt = getNextPrime(startAt)
ListBox1.Items.Add(startAt)
Next
End If
End Sub
''' <summary>
''' isPrime
''' </summary>
''' <param name="x"></param>
''' <returns></returns>
''' <remarks>a Prime Number is a number greater than 1 which is divisible only by itself and 1</remarks>
Private Function isPrime(ByVal x As Integer) As Boolean
If x < 2 Then Return False
Return Enumerable.Range(2, x - 2).All(Function(n) x Mod n <> 0)
End Function
Private Function getNextPrime(ByVal x As Integer) As Integer
Dim startAt As Integer = x + 1
Do
If isPrime(startAt) Then
Return startAt
Else
startAt += 1
End If
Loop
End Function
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
For c As Integer = 0 To Me.Width Step 25
e.Graphics.DrawLine(Pens.LightGray, c, 0, c, Me.Height)
Next
For r As Integer = 0 To Me.Height Step 25
e.Graphics.DrawLine(Pens.LightGray, 0, r, Me.Width, r)
Next
End Sub
End Class
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Sep 6th, 2012, 08:14 PM
#9
Re: Prime number generator
 Originally Posted by Evil_Giraffe
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 ?
-
Sep 7th, 2012, 03:19 AM
#10
Re: Prime number generator
 Originally Posted by Niya
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.
-
Sep 7th, 2012, 10:25 AM
#11
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:
Public MustInherit Class Yielder(Of T)
Implements IEnumerable(Of T)
Implements IEnumerator(Of T)
Private _current As T
Public Sub New()
End Sub
Protected MustOverride Function [Yield]() As T
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
Return Me
End Function
Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return Me
End Function
Public ReadOnly Property Current As T Implements System.Collections.Generic.IEnumerator(Of T).Current
Get
Return _current
End Get
End Property
Public ReadOnly Property Current1 As Object Implements System.Collections.IEnumerator.Current
Get
Return _current
End Get
End Property
Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
_current = [Yield]()
Return True
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
Throw New NotImplementedException()
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean = False
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Next I needed a class that will start calculating prime numbers and spit them out as they're found.
vb.net Code:
Public Class Primes
Inherits Yielder(Of Long)
Dim primes As New List(Of Long)
Dim candidate = 1
Protected Overrides Function [Yield]() As Long
Do While candidate <= Long.MaxValue
candidate += 1
If candidate = 2 Then
primes.Add(candidate)
Return candidate
End If
Dim IsPrime = Function(n) primes.TakeWhile(Function(p) p <= Math.Sqrt(n)).FirstOrDefault(Function(p) n Mod p = 0) = 0
If IsPrime(candidate) Then
primes.Add(candidate)
Return candidate
End If
Loop
Return Nothing
End Function
End Class
Here are a couple of examples using the Primes class.
vb.net Code:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim first25Primes = New Primes().Take(25).ToList()
Dim maxValue = 1000
Dim primesUnder1000 = New Primes().TakeWhile(Function(p) p <= maxValue).ToList()
Dim maxPrimeUnder1000 = New Primes().TakeWhile(Function(p) p <= maxValue).Max()
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.
-
Sep 7th, 2012, 03:23 PM
#12
Thread Starter
New Member
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
-
Sep 10th, 2012, 03:48 AM
#13
Re: Prime number generator
 Originally Posted by xerox3333
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:
 Originally Posted by xerox3333
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:
Public Class Form1 Private Sub btnRun_Click(sender As System.Object, e As System.EventArgs) Handles btnRun.Click 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} For Each prime In primes lstOutput.Items.Add(prime) Next End Sub 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.
-
Sep 10th, 2012, 08:41 AM
#14
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.
-
Sep 10th, 2012, 01:02 PM
#15
Re: Prime number generator
 Originally Posted by Evil_Giraffe
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|