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

How could I detect if a number is odd?

Asked by
ItsMeKlc 235 Moderation Voter
9 years ago

How could I detect if a number is an even/odd number?

1 answer

Log in to vote
4
Answered by
Necrorave 560 Moderation Voter
9 years ago

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!

Ad

Answer this question