PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Test for Odd or Even Numbers

Test for Odd or Even Numbers

Jun 23 2018, 2:02 AM PST

Problem

You want to know if any number is either odd or even.

Solution

Use the modulus operator to mod any number by 2.

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

Discussion

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

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

codeprint(5 % 3) 

Produces: 2

That is because 5/3 = 1 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. Since 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.

codeprint(3 % 2 == 0)

Produces: false

The above code checks to see what the remainder of 3/2 is. Then, it checks if the remainder is equal to 0 or not. Since the remainder is 1, it prints false. Note that 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 returns false when odd.

Several more examples:

code=print(6 % 2 == 0)

Produces: true

code=print(7 % 2 == 0)

Produce: false

code=print(1 % 2 == 0)

Produces: false

code=print(2353545678 % 2 == 0)

Produces: true

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 == 0
end
print(IsEven(363534))

Produces: true

Tags:
  • math
  • numbers