Is getal een priemgetal

Functie spreekt voor zich.
Kies Formules | Functie invoegen | Door gebruiker gedefinieerd
Geef een getal of celverwijzing op. Klaar! Voorbeeld:

In [A1] =dhIsPrime(99991)
Function dhIsPrime(ByVal lngX As Long) As Boolean
    ' Find out whether a given number is Prime.
    ' Treats negative numbers and positive numbers
    ' the same.
    
    ' From "VBA Developer's Handbook"
    ' by Ken Getz and Mike Gilbert
    ' Copyright 1997; Sybex, Inc. All rights reserved.
    
    ' In:
    '   lngX:
    '       Number to test if Prime
    ' Out:
    '   Return Value:
    '       Returns TRUE if the number is Prime
    
    Dim intI As Integer
    Dim dblTemp As Double
    dhIsPrime = True
    lngX = Abs(lngX)
    
    If lngX = 0 Or lngX = 1 Then
        dhIsPrime = False
    ElseIf lngX = 2 Then
        ' dhIsPrime is already set to True.
    ElseIf (lngX And 1) = 0 Then
        dhIsPrime = False
    Else
        For intI = 3 To Int(Sqr(lngX)) Step 2
            dblTemp = lngX / intI
            If dblTemp = lngX \ intI Then
                dhIsPrime = False
                Exit Function
            End If
        Next intI
    End If
End Function

© From “VBA Developer’s Handbook”
By Ken Getz and Mike Gilbert
Copyright 1997; Sybex, Inc. All rights reserved.

Leave a Reply

Your email address will not be published. Required fields are marked *