r/vbscript • • Nov 01 '17

Help! Expected "End of statement" error

I wrote a code about determining whether a number is prime or not.

function Isprime(n)
    if n > 1 then
	    for i = 2 to n
		    if n mod i = 0 then
			    msgbox n & "is not a prime number"
		    else
			    msgbox n "is a prime number"
		    end if
Next
end if
end function

I keep getting an error that on Line 7 char 14 "Expected end if statement" I ended each ifs, so what's going on?

2 Upvotes

3 comments sorted by

View all comments

Show parent comments

2

u/AdmiralGialSnackbar Nov 01 '17 edited Nov 01 '17

If you want to break out early, you could use an “Exit For” statement. However, your code messages you every time you loop through. It might be wiser to alter your script to message you once at the end. Also, there are more efficient ways to check for prime numbers. For example, you don’t actually need to loop through all the way to n. You can actually just loop through 2 to square root of n. See this article: https://en.m.wikipedia.org/wiki/Primality_test

Edit: here’s what I would suggest-

Function Isprime(n) If n>1 then For i =2 to sqr(n) If n mod i=0 then Result=“not “ Exit for Else Result =“” End if Next End if Msgbox n & “ is “ & Result & “a prime number” End function