Find Code:
All Words
Any of the Words
Exact Phrase
Home
:
Code
:
Forums
:
Submit
:
Mailing List
:
About
:
Contact
Code
All
VB.NET
ASP.NET
C#
VB Classic
ASP Classic
Snippets
Popular
Resources
Submit Code
Forums
Articles
Tips
Links
Books
Contest
Link to us
Prime number array class with timer
Author:
Steven
Submitted:
3/12/2012
Version:
VB 2010
Compatibility:
VB 2005, VB 2008, VB 2010
Category:
Mathematics
Views:
7427
Class to return all prime numbers from a start to end number as an array of longs with time in seconds.
Declarations:
'none
Code:
'Finds and returns all prime numbers as an array between the start and last number. Public Class GetPrimeArray Private primes(0) As Long Private start As Long = 1 Private last As Long = 100 Private ElapsedTime As Integer 'Sets the Start number Public WriteOnly Property setStart As Long Set(value As Long) start = value End Set End Property 'Sets the last number Public WriteOnly Property setLast As Long Set(value As Long) last = value End Set End Property 'Gets the prime array. Public ReadOnly Property GetPrimes() As Long() Get Return primes End Get End Property 'Gets the elapsed time in seconds. Public ReadOnly Property GetElapsedTime As Integer Get Return ElapsedTime End Get End Property 'loops through the range of numbers from an adjusted start to last and assigns primes to an array. Public Sub FindPrimeNumbers() Dim ArrayIndex As Integer Dim stpWatchInfo As New System.Diagnostics.Stopwatch 'Starts Timer stpWatchInfo.Start() 'initializes 1st element of array primes(0) = Nothing 'if start is 2 or less then sets 1st array element to 2 and start to 3 If start <= 2 Then primes(0) = 2 start = 3 End If 'if start is even then add 1 to start If start Mod 2 = 0 Then start += 1 End If 'if 1st element of array is nothing then set array index to 0 else to 1 If primes(0) = Nothing Then ArrayIndex = 0 Else ArrayIndex = 1 End If For x As Long = start To last Step 2 'at this point start is an odd number and testing even numbers is pointless hence step 2 'if number is prime then redeminsion the array and add number to end of array and incriment index If is_prime(x) Then ReDim Preserve primes(ArrayIndex) primes(ArrayIndex) = x ArrayIndex += 1 End If Next x 'stop timer and asign it to a private variable ElapsedTime = stpWatchInfo.Elapsed.Seconds End Sub 'check for prime and exit and return false as soon as multiple is found or return true Private Function is_prime(ByVal num As Long) As Boolean For x = 3 To Int(Math.Sqrt(num)) Step 2 ' only check to the square root of number as all unique multiples will have been checked. If num Mod x = 0 Then is_prime = False Exit Function End If Next x is_prime = True End Function End Class
Home
|
Forums
|
Submit
|
Books
|
Mailing List
|
Advertising
|
About
|
Contact
© 2024 A1VBCode. All rights reserved.
Legal disclaimer & terms of use
Privacy statement