Ad
Log in to vote
1

How do I detect if a number is odd or even? [closed]

Asked by 7 years ago

I've made a terrain system to generate blocks of terrain. To do this, it cuts certain vectors in half. But since it's a module script, if someone else put in an odd number, it would have a decimal number, which crashes the terrain system. So how do I detect an odd number so I can fix it?

Locked by adark, 2eggnog, and TofuBytes

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

2 answers

Log in to vote
2
Answered by
BlueTaslem 18054 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago

We can use the modulus "operator" % to determine the remainder after division of a number.

If x is even, then x % 2 is 0 since 2 goes evenly into an even number.


5 / 2 is 2 with a remainder of 1. 5 % 2 is that remainder (1)


Examples:

1 % 3 is 1

2 % 3 is 2

3 % 3 is 0

4 % 3 is 1

5 % 3 is 2

6 % 3 is 0

7 % 3 is 1

8 % 3 is 2

9 % 3 is 0

10 % 3 is 1


It even works with fractions:

1 % 1.5 is 1

1.5 % 1.5 is 0

2 % 1.5 is 0.5

2.5 % 1.5 is 1

3 % 1.5 is 0

3.5 % 1.5 is 0.5

4 % 1.5 is 1


A warning about the sign (positive / negative) of the result:

The sign of a % b matches the sign of b (in Lua). So:

  • 5 % (-2) is -1
  • (-5) % (-2) is -1
  • (-5) % 2 is 1
0
Thanks a ton! ChipioIndustries 454 — 7y
Ad
Log in to vote
1
Answered by
2eggnog 981 Moderation Voter
7 years ago

Simply use a modulo (%). It's used to find the remainder when dividing by something. When dividing by 2, if the remainder is 0, the number is even. Otherwise, it's odd.

if (number%2) == 0 then
--number is even
else
--number is odd
end
2
BlueTaslem keeps beating me to questions. 2eggnog 981 — 7y
1
:) BlueTaslem 18054 — 7y