Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Checking if a number is odd or even?

Asked by 8 years ago

Simple question. Hopefully a simple answer. Now I've scowled at the math function dump (Wiki for what seems like forever, looking for a way to check if a # is prime or not. I've had no luck.

Maybe I read the wiki page the wrong way, maybe I didn't. Here's an example for how I'd use a math function to check if something is odd or even:

Example = math.oe(7) --"oe" stands Odd, Even
if Example == true then --the function would output true if it e=is even and false if it isn't
    --do stuff
end

2 answers

Log in to vote
2
Answered by
Kryddan 261 Moderation Voter
8 years ago

There is an arithmetic operator in Lua that is called modulus(%) that divides two numbers and then returns the remainder. For example, 5%2 will return 1 because 2 goes two times into 5 and the remainder will be 1, 2*2 =4 5-4=1. So if any number divided by 2 got a remainder of 1 then the number is odd, if not then it's even. Are you with me so far?

local Example = 7
if Example%2 == 0 then
    print("even")
else
    print("odd")
end
Ad
Log in to vote
1
Answered by 8 years ago

Use modulus %

If it goes evenly into %# then there will be no remainder

print(4%2) --0 Even number
print(3%2) --1 Odd number

Answer this question