# VB.NET - Code Samples - Find Prime Numbers Algorithm

## VB.NET Prime Number Searching

### Synopsis:

This is an algorithm created for a contest on vbforums.com . Pass the function the number of primes you want to generate and it will return them as an int32 array.

### The Code:

```   Private Function GeneratePrimeList2(ByVal numOfPrimes As Int32) As Int32()
Dim primes(numOfPrimes - 1) As Int32
Dim cntr As Int32 = 5
Dim pcntr As Int32 = 2
Dim i As Int32

Dim maxPrimeSqrRoot As Double

primes(0) = 2
primes(1) = 3

Do Until pcntr = numOfPrimes

'get the highest factor to check against if under the
'predetermined maximum
maxPrimeSqrRoot = Math.Sqrt(cntr)
'for each prime other than two
For i = 1 To pcntr - 1
'check for clean division
If cntr Mod primes(i) = 0 Then
'not prime
Exit For
Else
'if all primes up to maxfactor used or all primes used then it is prime
If primes(i + 1) > maxPrimeSqrRoot OrElse i = pcntr - 1 Then
primes(pcntr) = cntr
pcntr += 1
Exit For
End If
End If
Next
cntr += 2
Loop
Return primes

End Function
```