English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have this problem in which i need an algorhythm which can tell if an number is even or odd. I need help!!!! BUT! i'm not working with java or c++ or anything, it's a normal "technical" language. what I have so far doesn't work!!! i need help please

To be a bit more specific, i need the formula for the computer to identify the numbers.

2007-09-09 10:10:43 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

3 answers

I'm assuming you don't have a modulo operator. Do integers truncate? If so, we can do this the hard way:

All variables are integer.

N is the number

define H=N/2 (assuming truncation)

If N> Hx2, the number was odd

If H>2, copy H to N and start over.

If you get to the end here, the number was even.

2007-09-09 10:24:33 · answer #1 · answered by Computer Guy 7 · 0 1

The best, fastest, and easiest way to do this, is by using the bitwise AND operator like follows:

10 IF x &1 EQUALS TO 0 THEN
20      x IS Even
30 ELSE
40      x IS Odd

In Java for example, you will write it like:
public static boolean isEven(int x) {
     return (x & 1) == 0;
}

That works because odd numbers always have a high LSB (Least Significant Bit) in their Binary Representation, so if we bitwise anded an odd number with 1, and the result comes to be zero, then the LSB of the original number was low, which means it was an even number, if the result comes to be high (i.e. one) then the original number was itself an odd one.

Thanks.

2007-09-09 17:51:57 · answer #2 · answered by Fox 3 · 0 0

In most languages, there is an operator called "modulo," "residue," "remainder." In many, the % is used for the operator. The expression x%2 (read "X modulo 2") evaluates to the remainder of division of x by 2. For instance, 5%2 = 1 (that is, 5/2 = 2 remainder of 1) and 6%2 = 0 (that is, 6/2 = 3 remainder of 0).

If you have a mod operator in the language you're using, the rule for odd/even is very simple.

if (0 == x%2) the x is even
if (1 == x%2) the x is odd

2007-09-09 17:33:29 · answer #3 · answered by richarduie 6 · 1 2

fedest.com, questions and answers