How could I detect if a number is an even/odd number?
COMMUNITY QUESTION
How could I detect if a number is odd?
1 answer
Using the Mod operator or %
What does it do?
The mod operator is basically another way to divide values, but instead of returning the result, it returns the remainder.
Example:
local z = 10 % 2 --This is like 10 / 2 but it will return whats left over
print (z) --This will print 0 because there is no remainder
z = 10 % 3 -- This should not evenly divide
print (z) --This will now print '1', or the remainder
How you could use this
Basically, if you divide a number by two and it has no remainder, it is an even number.
So to check if something is an odd number, you can have it check if the remainder has any value other than 0
if x % 2 == 0 then
print (x.." is an even number")
else
print (x.." is an odd number")
end
Try experimenting with this and let me know if it works for you!
This discussion is preserved as it was. New answers, comments, and votes are closed.
