Thread: odd or even
View Single Post
  #4 (permalink)  
Old 09-29-2008, 08:58 AM
curtiss's Avatar
curtiss curtiss is offline
Moderator
 
Join Date: May 2003
Posts: 1,468
I don't think that's quite right. I'm not sure if you're understanding the modulus operator quite right.

The modulus operator divides number A by number B. Then, rather than returning the dividend (the result of A divided by B), it returns the remainder that's left over. Here are some samples with real numbers to help you understand:

1 % 1 = (1/1 = 1, exactly; there is no remainder, so the answer is going to be 0)
2 % 2 = (2/2 = 1, exactly; there is no remainder, so the answer is going to be 0)
3 % 2 = (3/2 = 1 with a remainder of 1, so the answer is going to be 1)
25 % 13 = (25/13 = 1 with a remainder of 12, so the answer is going to be 12)
47 % 12 = (47/3 = 3 with a remainder of 11, so the answer is going to be 11)

Therefore, to find even or odd, all you do is use the modulus operator to find the remainder when divided by 2. Here are some more examples:
1 % 2 = (1/2 = 0 with a remainder of 1, so that odd number will return 1 as its remainder)
2 % 2 = (2/2 = 1 with a remainder of 0, so that even number will return 0 as its remainder)
3 % 2 = (3/2 = 1 with a remainder of 1, so that odd number will return 1)
4 % 2 = (4/2 = 2 with no remainder, so it returns 0)
5 % 2 = (5/2 = 2 with remainder 1, so it returns 1)
6 % 2 = (6/2 = 3 with no remainder, returns 0)
7 % 2 = (7/2 = 3, remainder 1, returns 1), etc., etc., etc.

All even numbers will return 0 as their remainder; all odd numbers will return 1 as their remainder.

I'm not sure what 0 % 2 would return. I would imagine that it would throw a "divide by zero" error, but I'm not certain. Therefore, it's probably a good idea to check to make sure your number is not 0 (or empty) before testing its remainder. It's probably also a good idea to make sure that it "is_numeric".
__________________
I hate Internet Explorer! Anyone with me?
Reply With Quote