Finding if a number is even or odd: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Quenty
Created page with "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 th..."
 
>Quenty
Created page with "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 th..."
(No difference)

Revision as of 07:11, 29 February 2012

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 = one, which is ignored, with a remainder of 1. 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(1 == (3 % 2))  
--> 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 middle 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(1 == (6 % 2))
--> true

print(1 == (7 % 2))
--> false

print(1 == (1 % 2))
--> false

print(1 == (2353545678 % 2))
--> true

print(1 == (3333333333333333333333333333333333333333333333333333333332 % 2))
--> true

print(1 == (3333333333333333333333333333333333333333333333333333333333 % 2))
--> 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 1 == (num % 2)
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