## ProblemYou want to store and retrieve a lot of bits without wasting memory and without sacrificing speed of operation. ## SolutionSample code folder: Chapter 06\GetPrimes Use a ## DiscussionThe To demonstrate using a The Sieve of Eratosthenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) works by first setting all bits to 1, or The Eratosthenes module contains the Module Eratosthenes Private Const MaxNumber As Integer = 8000000 Private PrimeStorage As New BitArray(MaxNumber, True) Public Sub Sieve() ' ----- Get all the prime numbers from 1 to MaxNumber. Dim index As Integer = 1 Dim counter As Integer ' ----- Scan through all primes. Do While (index < (MaxNumber - 1)) index += 1 If (PrimeStorage(index) = True) Then ' ----- Found a prime. Set all of its multiples ' to non-prime. For counter = index * 2 To MaxNumber - 1 _ Step index PrimeStorage(counter) = False Next counter End If Loop End Sub Public Function GetBit(ByVal index As Integer) As Integer ' ----- Retrieve the status of a single prime bit. If (PrimeStorage(index) = True) Then _ Return 1 Else Return 0 End Function End Module The following block of code demonstrates the Dim result As New System.Text.StringBuilder Dim counter As Integer Dim needBreak As Boolean = True result.AppendLine( _ "Prime numbers using the ""Sieve of Eratosthenes""") ' ----- Generate the primes. Sieve() ' ----- Report each prime. For counter = 2 To 7999999 If (GetBit(counter) = 1) Then If (counter < 50) Or (counter > 7999800) Then ' ----- Only show a limited number of primes. result.AppendLine(counter) ElseIf (needBreak = True) Then ' ----- Show that we are leaving something out. result.AppendLine("…") needBreak = False End If End If Next counter MsgBox(result.ToString()) Figure 6-25 shows the partial list of all the prime numbers as determined by the bits in the ## Figure 6-25. All the prime numbers between 0 and 8,000,000, calculated quickly using a BitArray## See AlsoSearch for "prime numbers" on the Web for more information. See also "Logical and Bitwise Operators in Visual Basic" in the Visual Studio online help. |

Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

ISBN: 0596101775

EAN: 2147483647

EAN: 2147483647

Year: 2006

Pages: 400

Pages: 400

Authors: Tim Patrick, John Craig

Similar book on Amazon

- Using SQL Data Definition Language (DDL) to Create Data Tables and Other Database Objects
- Working with Comparison Predicates and Grouped Queries
- Writing External Applications to Query and Manipulate Database Data
- Working with Ms-sql Server Information Schema View
- Working with SQL Database Data Across the Internet

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net