Prime number controller is incredibly slow

I have this piece of code that checks to see if a given number is prime:

If x Mod 2 = 0 Then
    Return False
End If
For i = 3 To x / 2 + 1 Step 2
    If x Mod i = 0 Then
        Return False
    End If
Next
Return True

I use it only for numbers 1E7 <= x <= 2E7. However, it is very slow - I can barely check 300 numbers per second, so checking all xwill take more than 23 days ...

Can someone give some suggestions for improvement or say what I could do unnecessarily this way?

+3
source share
9 answers

! Fermat. , , . .

+3

" ". , , . .

+4
+3

x/2 + 1 , , For. , . .

+1

, Set, , . , Set, , . .

+1

Divide the range in some fragments and do checks in two or more threads if you have a multi-core processor. Or use Parallel.For.

0
source

To check if a number is prime, you check to see if it is divisible by primes and then by it.

Please check the following snippet:

 Sub Main()

        Dim primes As New List(Of Integer)
        primes.Add(1)

        For x As Integer = 1 To 1000
            If IsPrime(x, primes) Then
                primes.Add(x)
                Console.WriteLine(x)
            End If
        Next

    End Sub

    Private Function IsPrime(x As Integer, primes As IEnumerable(Of Integer)) As Boolean
        For Each prime In primes
            If prime <> 1 AndAlso prime <> x Then
                If x Mod prime = 0 Then
                    Return False
                End If
            End If
        Next
        Return True
    End Function
0
source

it is slow because you are using x / 2. I changed your code a bit. (I don't know about VB syntax, maybe you need to change your syntax.)

If x < 2 Then
    Return False
IF x == 2 Then
    Return True
If x Mod 2 = 0 Then
    Return False
End If
For i = 3 To (i*i)<=x Step 2
    If x Mod i = 0 Then
        Return False
    End If
Next
Return True
0
source

Source: https://habr.com/ru/post/1791817/


All Articles