0

I tried this function to give me Prime Number but it ain't working. I can't think of anything. I can do this easily in JS but here it just gives me headache.

Function JeLiProst(N As Integer) As Boolean
If N = 0 Then JeLiProst = False
If N = 1 Then JeLiProst = False
If N = 2 Then JeLiProst = True
For I = 2 To N - 1
If N Mod I = 0 Then 
JeLiProst = False
Else
JeLiProst = True
End If
End Function
braX
  • 11,506
  • 5
  • 20
  • 33
  • 3
    I haven't used vba in a million years but shouldn't you break the loop and exit the function with false as soon as `N Mod I = 0` is true? – Joakim Danielson Mar 23 '20 at 08:39
  • 1
    And a `Next I` is missing. – Pᴇʜ Mar 23 '20 at 09:07
  • Possible duplicate of [Prime number for n value](https://stackoverflow.com/questions/60098497/prime-number-for-n-value) – T.M. Mar 23 '20 at 09:07
  • @JoakimDanielson Honestly I tried doing this, ```For I = 2 To N - 1 If N Mod I = 0 Then GoTo Fal Next JeLiProst = True Fal: JeLiProst = False ``` Didnt do much, now not even if 2 = true condition work – DrexxBoban Mar 23 '20 at 09:10
  • Either I or the community member who judged this to be a duplicate didn't understand the question. In my opinion the referenced "Duplicate" bears no similarity to this question whatsoever. I have posted an answer. Let the OP decide if it's useful. – Variatus Mar 23 '20 at 09:26
  • @Variatus The OP believes that `JeLiProst = False` works like `return false` in javascript. Their key misconception is that this assignment exits the function. The duplicate question shows how it is not the case and what to do instead. The *purpose* of the function (to test for prime number) is not even relevant at that point. – GSerg Mar 23 '20 at 11:38
  • @GSerg Thank you. Interesting perspective. – Variatus Mar 23 '20 at 11:58

1 Answers1

-2

Does this function do what you want?

Function JeLiProst(N As Integer) As Boolean

    Dim Primes As Variant
    Dim i As Integer

    ' prime numbers below 50. Extend if required.
    Primes = Array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)

    If N > 1 Then
        For i = 0 To UBound(Primes)
            If Primes(i) > N Then
                JeLiProst = True
                Exit For
            Else
                If (N Mod Primes(i)) = 0 Then
                    JeLiProst = (N = Primes(i))
                    Exit For
                End If
            End If
        Next i
        If i > UBound(Primes) Then
            MsgBox N & " appears to be a prime number but I lack" & vbCr & _
                   "the data to assert that as a definite fact." & vbCr & _
                   "I shall classify it as 'not prime'.", _
                   vbInformation, "Insufficient stored data"
        End If
    Else
        JeLiProst = True
    End If
End Function
Variatus
  • 14,293
  • 2
  • 14
  • 30