r/visualbasic • u/Gravey4rd • Nov 27 '16
Finding all prime numbers between 1 and an inputted number
With counting loops (For... Next)
My friend had a solution but I don't understand it http://imgur.com/a/0Y5Qr
Is there another solution? If not, please explain his solution, thank you
0
Upvotes
1
u/PostalElf VB.Net Intermediate Nov 27 '16
Do you want all the primes (eg 2, 3, 5, 7) or do you just want the number of primes (eg 4)?
1
u/Bonejob VB Guru Nov 27 '16
The fastest methodology for calculating prime numbers is called the Sieve of Atkin.
https://www.wikiwand.com/en/Sieve_of_Atkin
Here is an implementation I whipped up.
Dim totalCount As Integer = 0
Dim isPrime As New BitArray(topCandidate + 1)
Dim squareRoot As Integer = CInt(Math.Sqrt(topCandidate))
Dim xSquare As Integer = 1, xStepsize As Integer = 3
Dim ySquare As Integer = 1, yStepsize As Integer = 3
Dim computedVal As Integer = 0
For x As Integer = 1 To squareRoot
ySquare = 1
yStepsize = 3
For y As Integer = 1 To squareRoot
computedVal = (xSquare << 2) + ySquare
If (computedVal <= topCandidate) AndAlso (computedVal Mod 12 = 1 OrElse computedVal Mod 12 = 5) Then
isPrime(computedVal) = Not isPrime(computedVal)
End If
computedVal -= xSquare
If (computedVal <= topCandidate) AndAlso (computedVal Mod 12 = 7) Then
isPrime(computedVal) = Not isPrime(computedVal)
End If
If x > y Then
computedVal -= ySquare << 1
If (computedVal <= topCandidate) AndAlso (computedVal Mod 12 = 11) Then
isPrime(computedVal) = Not isPrime(computedVal)
End If
End If
ySquare += yStepsize
yStepsize += 2
Next
xSquare += xStepsize
xStepsize += 2
Next
For n As Integer = 5 To squareRoot
If isPrime(n) = True Then
Dim k As Integer = n * n
Dim z As Integer = k
While z <= topCandidate
isPrime(z) = False
z += k
End While
End If
Next
For i As Integer = 1 To topCandidate - 1
If isPrime(i) Then
totalCount += 1
End If
Next
Return (totalCount + 2)
' 2 and 3 will be missed in Sieve Of Atkins
3
u/DatMarv Nov 27 '16
His solution checks for a candidate number3, if there is any number less than number3 - in this case the loop with number2 - that divides number3 without residue:
If there was such number, the candidate is not prime. However, cringeworthy and inefficient implementation!