The above code is a great example, but there is a way to make it faster. Consider the following:
Input number: 100
100 / 2: 50
Sqr(100): 10
Once you hit the
square root of a number, you can stop, as it is likely to be a great deal smaller than the same number halved. Here's how I would do this (this is in fact an update of the program I used to learn QBASIC, which some of you may remember from the days of MS-DOS):
First, the IsPrime Function:
Function IsPrime(checkValue As Long) As Boolean
For testValue = 2 To CLng(Sqr(checkValue)) Step 1
If checkValue Mod testValue = 0 Then
IsPrime = False
Exit Function
End If
Next
IsPrime = True
End Function
And now for the code which will use the IsPrime function to solve your problem:
Sub Main()
Do
userValue = CLng(InputBox("Enter a value to test. I will tell you if it is prime or not.", "Prime Tester", userValue))
If IsPrime(userValue) Then
If MsgBox(userValue & " is a prime number! Congratulations! Would you like to try another?", vbYesNo, "Number is Prime!") = vbNo Then
End
End If
End If
Loop
End Sub
Just for kicks and giggles (and since the program I'm redoing to bring you this solution did it this way too), I'll provide the code to list every number LESS THAN the user's input that is a prime number, taking advantage of the IsPrime Function again:
Sub Main()
Do
userValue = CLng(InputBox("Enter a value to test. I will tell you every prime up to (and possibly including) it.", "Prime Tester", userValue))
primesList = "1"
For countValue = 2 To CLng(userValue) Step 1
If IsPrime(CLng(countValue)) Then
primesList = primesList & ", " & CStr(countValue)
End If
Next
If MsgBox("The prime numbers up to (and possibly including) " & userValue & " are:" & vbCrLf & primesList & vbCrLf & vbCrLf & "Would you like to try another?", vbYesNo, "Your Prime Numbers") = vbNo Then
End
End If
Loop
End Sub
Other variations include the smallest prime >= <input number>, the largest prime <= <input number>, the first <input number> prime numbers, or any number of other things you might use the IsPrime function to do. This is a (relatively) quick function, and takes a mere fraction of the time you would use checking every number up to <input number> / 2 - especially for larger numbers.
As always, enjoy!
- Sendoshin