How can I test for primality?

前端 未结 16 2215
南方客
南方客 2020-12-05 08:29

I am writing a little library with some prime number related methods. As I\'ve done the groundwork (aka working methods) and now I\'m looking for some optimization. Ofcours

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 08:46

    In case anyone else is interested, here's my conversion of Mohammad's procedure above to VBA. I added a check to exclude 1, 0, and negative numbers as they are all defined as not prime.

    I have only tested this in Excel VBA:

    Function IsPrime(input_num As Long) As Boolean
        Dim i As Long
        If input_num < 2 Then '1, 0, and negative numbers are all defined as not prime.
            IsPrime = False: Exit Function
        ElseIf input_num = 2 Then
            IsPrime = True: Exit Function '2 is a prime
        ElseIf input_num = 3 Then
            IsPrime = True: Exit Function '3 is a prime.
        ElseIf input_num Mod 2 = 0 Then
            IsPrime = False: Exit Function 'divisible by 2, so not a prime.
        ElseIf input_num Mod 3 = 0 Then
            IsPrime = False: Exit Function 'divisible by 3, so not a prime.
        Else
            'from here on, we only need to check for factors where
            '6k ± 1 = square root of input_num:
            i = 5
            Do While i * i <= input_num
                If input_num Mod i = 0 Then
                    IsPrime = False: Exit Function
                ElseIf input_num Mod (i + 2) = 0 Then
                    IsPrime = False: Exit Function
                End If
                i = i + 6
            Loop
            IsPrime = True
        End If
    End Function
    

提交回复
热议问题