Mit dieser Funktion lässt sich eine Menge großer Primzahlen weitaus schneller berechnen. Zum Vergleich:
Slow: 664579 primes < 10^7 computed in 00:08.6306629
Fast: 664579 primes < 10^7 computed in 00:05.2659327
Slow: 5761455 primes < 10^8 computed in 04:52.4940141
Fast: 5761455 primes < 10^8 computed in 03:07.4373887
mm:ss.ms
Function Slow(ByVal n As Integer) As Boolean
If n Mod 2 = 0 OrElse n Mod 3 = 0 OrElse n Mod 7 = 0 OrElse n Mod 5 = 0 Then Return False
For i As Short = 11 To Math.Sqrt(n) Step 2
If n Mod i = 0 Then Return False
Next
Return True
End Function
Function Fast(ByVal n As Integer) As Boolean
If n Mod 2 = 0 OrElse n Mod 3 = 0 OrElse n Mod 7 = 0 OrElse n Mod 5 = 0 Then Return False
Dim r As Single = Math.Sqrt(n), f As Short = 11
If r Mod 1 = 0 Then Return False
While f <= r
If n Mod f = 0 Then Return False
f += 2
If n Mod f = 0 Then Return False
f += 4
End While
Return True
End Function
3 Kommentare zum Snippet