Finding if a number is even or odd

From Legacy Roblox Wiki
Jump to navigationJump to search

Finding if a number is even or odd can be confusing for newcomers. However, the solution is simple using a modulus, function.

The % symbol used in programming tells what the remainder is when 2 the two numbers are divided. For example

print(5 % 3)
2

because 5/3 = 1, which is ignored, with a remainder of 2. So basically modulus gives you the remainder of 2 numbers being divided.

Using this, we can figure out if a number is even or odd by seeing if the remainder is 1 or 0 when dividing by 2. Because odds when divided by two have a remainder of 1, and evens have a remainder of 0, we can determine if it's odd or even.

print(3 % 2 == 1)
true

The above code check to see what the remainder of 3/2 is in 3 % 2, which is 1. Then, it checks if the remainder is equal to 1 or not. And it is. So it prints true. Note all you are changing is the first number, which is the number you are checking to see if it is even or odd. Also note that it gives a true value when even, and a false when odd.

Several more examples:

print(6 % 2 == 1)
false
print(7 % 2 == 1)
false
print(1 % 2 == 1)
false
print(2353545678 % 2 == 1)
true
print(3333333333333333333333333333333333333333333333333333333332 % 2 == 1)
true
print(3333333333333333333333333333333333333333333333333333333333 % 2 == 1)
false

So knowing that all we change is the middle value, we don't want to keep on typing that long statement. We want to put it in a function.

A function to find if it is even or odd would look like this.

function IsEven(num)
	return num % 2 == 1
end

print(IsEven(363534))
true

In the above function, 'IsEven' is the function name. num is the number we are checking if even or odd, and return 'returns' a value when calling the function.

So now you know why and how to determine if a number is even or odd, and hopefully understand it too.

See Also