PDA

View Full Version : Need VBA code to display 1st PRIME number greater than value (N)



cramer2828
06-04-2014, 09:34 AM
find the first PRIME number greater than a given number N. So for example, if N is 10 it should return 11, and if N is 24 it should return 29 (since 25-28 are not prime numbers.)

Any help would be much appreciated, I'm not even sure where to start. Thank you.

EirikDaude
06-05-2014, 12:47 AM
I'd start with doing something like this (http://lmgtfy.com/?q=prime+number+algorithm+vba).

GTO
06-05-2014, 02:27 AM
Hi Erik,

I did not check any of the hits, but just had to comment... Tears, can't see, too funny!!!

Mark

Paul_Hossler
06-05-2014, 06:31 AM
Is this for developing an algorithm (e.g. homework)? Is there a upper limit?

Otherwise, the fastest way would be be to just load a list of the first 10,000 or so numbers and use =MATCH()

JKwan
06-05-2014, 08:12 AM
using what Erik posted (too funny), this is what I came up



Private Function IsDecimal(Number) As Boolean
Dim splitted() As String
splitted = Split(Number, ".")
If UBound(splitted) <> 0 Then
IsDecimal = True
End If
End Function
Private Function IsPrimeNumber(Number) As Boolean
For i = 2 To Number - 1
If IsDecimal(Number / i) = False Then
IsPrimeNumber = False
Exit Function
End If
Next i
IsPrimeNumber = True
End Function
Public Function NextPrime(Number As Long) As Long
Dim lCheckPrimeNumber As Long
Dim bPrime As Boolean

lCheckPrimeNumber = Number
Do
lCheckPrimeNumber = lCheckPrimeNumber + 1
bPrime = IsPrimeNumber(lCheckPrimeNumber)
If bPrime Then
NextPrime = lCheckPrimeNumber
End If
Loop While Not bPrime
End Function