Helpful Information
 
 
Category: Software Design
Puzzle: Find the error in this algorithm.

I figure that this forum could use a puzzle or two, once in a while. So here's my first effort --- basically the idea is to find if there is a flaw in the logic below:

Algorithm to determine odd or even number:

1. Perform a modulo divide operation by 2 on the number to get the reminder.
2. If the reminder is 1, the number is odd, otherwise the number is even.

Expressed in C, the code would look something like this:


#include <stdio.h>

void odd_even(int x) {
if ((x % 2) == 1)
printf("%d is odd\n", x);
else
printf("%d is even\n", x);
}

int main() {
odd_even(2);
odd_even(1);
}


So, is there anything wrong with this algorithm. Post your replies here.

Well, first of all this could done much easier using a bitwise AND with 1, which would also fix the flaw in the algorithm, namely that -1 (or any odd negative number for that matter) will be marked as even because -1%2 = -1.

Congratulations Andaness, you found the right answer! I didn't think the puzzle would be cracked so quickly :). One other way to fix it would be to reverse the check as in:



if (number modulo 2) = 0 then
it is an even number
else
it is an odd number


This will also work with negative numbers.

The bitwise AND is the more efficient way to determine if this is an odd or even number, but the modulo method was discussed for the purposes of this puzzle. (NOTE: For all the new readers in this forum, the bitwise AND algorithm was discussed earlier in http://forums.devshed.com/showthread.php?s=&threadid=29843&forumid=43 Check out the difference in the size of the code using the modulo method and the bitwise method and you'll clearly see where the efficiency comes from.)










privacy (GDPR)