C0D3 MA5T3R Homepage

Prime Number Checker

Function to check whether a number is prime

(See Below Code)

'Call the Prime Function, with the number to check as the parameter
Public Function Prime(number As Variant)

'set c to begin checking the number with 2
c = 2

1

'Set Errortrap to protect against invalid numbers - e.g. strings
On Error GoTo Invalid

'Divide number by c to see if it will divide fully
b = number / c
'Check to see if it has divided fully - if it has then the integar value of b will be the same as b itself
If Int(b) = b Then Prime = 0: GoTo done 'It is divisible by c so is not prime, set prime to show that then goto done

'Add one to c to check number with a new value next time
c = c + 1

'If c is over halfway of a then there will be no more combinations
If c > number / 2 Then finished = 1 'Set finished to show checking is over

'Check to see if Checking has finished
If finished = 0 Then GoTo 1 'If it hasn't, go back to 1
'If it has, then set Prime to show that no divisible numbers were found - i.e. it is a prime number
Prime = 1
'Goto done to exit the function
GoTo done

'If an error occurs, the program goes to Invalid
Invalid:
'Set Prime to show an error has occured - e.g. number was a string value etc.
Prime = 2

'done
done:
End Function

'An example of how the function could be called:
Private Sub Command1_Click()
result = Prime(Text1.Text)
If result = 0 Then MsgBox "Not Prime!"
If result = 1 Then MsgBox "Prime!"
If result = 2 Then MsgBox "Error!"
End Sub

(Copy and Paste this code into your Visual Basic project)

*Want to join the C0D3 MA5T3R e-mail list?*

Get all the latest code news and articles, and even submit your own.

You can sign-up for free below (you may opt-out at any time):

Join the mailing list
Enter your name and email address:
Name:
Email:  
Subscribe      Unsubscribe