Frnds, My questions is "how come to know whether the number is even or odd without using %,/,bitwise operator".

Recommended Answers

All 17 Replies

if any number modulus 2 is zero then it's even otherwise it's an odd number so your condition would be
if (Num%2==0) sop("EVEN");

I guess you didn't read the bit about not using %

Can you use shift operators?

oops sorry.

without using %

The (definitive) Java Language Spec describes 'bitwize" operators in section 15.22, but shift operators in section 5.19, which to me confirms that shift operators are not "bitwize" operators, so are not forbidden for this exercise.

So: shift your number one bit right, then back 1 bit left again, and if its value is still the same then last bit must have been 0, so the number must have been even.

@jamesCherrill, Ok shift is not bitwize operator. But i didnt get the the solution you are saying about shifting. Please explain it with example.

Shift 1 bit to the right... the rightmost bit will be lost.
Then shift back 1 place to the left and a zero will be used to fill the last bit.

A small eg: consider these two numbers (4 bits for simplicity)
0111 (7, an odd number)
0010 (2, an even number)
shift 1 right...
0011
0001
now shift one back to the left
0110 (was 7, now 6)
0010 (2 again)

So those shifts just replace the last bit with a zero, leaving even numbers unchanged, but odd numbers changed to a 1-smaller even number, ie

0111 == 0110 false, number is not even
0010 == 0010 true, number is even

Thanks JamesCherrill, First i have taken number as string and then checked its last digit whether its last digit is 0,2,4,6,8. if it is then number is EVEN else ODD

If you are going check the last character of a string, you could convert to binary and then just check for "0" or "1".

    public static String isOddOrEven(int num)
    {

        String binaryStr = Integer.toBinaryString(num);      
        if (binaryStr.charAt(binaryStr.length() - 1) == '0')
        {
            return "even";
        }
        else
        {
            return "odd";
        }    
    }

Is this a homework assignment? If so, I think that you're missing the point of the lesson. What is the current subject matter? Some possible lessons that are trying to be taught are:

  • Numeric approximation, rounding, truncation
  • Arithmetic overflow
  • Arithmetic underflow

The following will (eventually) result in an invalid result because of the effects of numeric approximation, rounding and truncation:

private static String isOddOrEven10(int num)
{
    String result = "";

    double tempNumDbl = (double)num * 0.1;

    int tempNumInt = (int)tempNumDbl;

    double tempNumSubDbl = tempNumDbl - tempNumInt;

    int lastDigit = (int)(tempNumSubDbl * 10.0);


    //int lastDigit = (int)((tempNumDbl - (int)tempNumDbl) * 10.0);

    switch(lastDigit)
    {
        case 0:
            result = "even";
            break;
        case 2:
            result = "even";
            break;
        case 4:
            result = "even";
            break;
        case 6:
            result = "even";
            break;
        case 8:
            result = "even";
            break;
        default:
            result = "odd";
    }//switch

    return result;
}

Output:

Num: 41
41.0 x 0.1 = 4.1
(int)4.1 = 4
4.1 - 4 = 0.10000000000000053
0.10000000000000053 x 10.0 = 1.0000000000000053
(int)1.0000000000000053 = 1

Result: 1 is odd, so 41 is odd.

Num: 42
42.0 x 0.1 = 4.2
(int)4.2 = 4
4.2 - 4 = 0.20000000000000018
0.20000000000000018 x 10.0 = 2.0000000000000018
(int)2.0000000000000018 = 2

Result: 2 is even, so 42 is even.

Num: 43
43.0 x 0.1 = 4.3
(int)4.3 = 4
4.3 - 4 = 0.2999999999999998
0.2999999999999998 x 10.0 = 2.999999999999998
(int)2.999999999999998 = 2

Result: 2 is even, so 43 is even??? What happened? The last digit was 3, and now it is showing up as 2.

So, a better way would be:

private static String isOddOrEven2(int num)
{
    String result = "";

    double tempNumDbl = (double)num * 0.5;

    int tempNumInt = (int)tempNumDbl;

    double tempNumSubDbl = tempNumDbl - tempNumInt;

    int lastDigit = (int)((tempNumDbl - (int)tempNumDbl) * 2.0);

    if (lastDigit == 0)
    {
      result = "even";
    }
    else
    {
        result = "odd";
    }

    return result;
}

Output:

Num: 41
41.0 x 0.5 = 20.5
(int)20.5 = 20
20.5 - 20 = 0.5
0.5 x 2.0 = 1.0
(int)1.0 = 1

Result: 1 is odd, so 41 is odd.

Num: 42
42.0 x 0.5 = 21.0
(int)21.0 = 21
21.0 - 21 = 0.0
0.0 x 2.0 = 0
(int)0.0 = 0

Result: 0 is even, so 42 is even.

Num: 43
43.0 x 0.5 = 21.5
(int)21.5 = 21
21.5 - 21 = 0.5
0.5 x 2.0 = 1.0
(int)1.0 = 1

Result: 1 is odd, so 43 is odd.

You may notice, that using this one, the only two results are 0 or 1.

Here's an article of interest. A data conversion caused a rocket named Ariane 5 to crash.

Hi,

I don't know if I came too late, but there's a simple solution, especially if the exercise concerns loops, you can make successive subtraction of 2 util the value is less than 2, if the final result is 0 then the number is even, otherwise the number is odd.

@Tarek_2: That might be ok for small numbers, but what about when you approach Integer.MaxValue (2,147,483,647)?

@cgeier:
I wrote this to test it out (as I was curious):

public int countdown()
{
    int i = Integer.MAX_VALUE;
    while (i > 2)
    {
        i -= 2;
    }
    return i;
}

It took less than a second to return 1...

Interesting...

You could start by subtracting higher powers of 2 and do that in just thirty passes of the loop. Pseudo-code:

int pot = 2 to the power 30 (hex 40 00 00 00)
while (pot >= 2)
   if (i > pot) i -= pot;
   pot = pot >> 1  // 2 to the power 29, 28, 27 etc
return i

ps; anybody thought about negative numbers?

I also became curious. So I timed the execution. On my computer, the method that uses subtraction (as posted above) averaged 600 ms. Then one that uses multiplication averaged 0 ms.

Check it out:

Method 1:

private static String isOddOrEvenMultiply(int num)
{
    double tempNumDbl = (double)num * 0.5;
    int tempNumInt = (int)tempNumDbl;
    double tempNumSubDbl = tempNumDbl - tempNumInt;
    int lastDigit = (int)(tempNumSubDbl * 2.0);

    if (lastDigit == 0)
    {
      return "even";
    }
    else
    {
        return "odd";
    } 
}

Method 2:

Note: Some minor modifications were made to the below method. See above for the original supplied by @TylerD75.

private static String isOddOrEvenSubtract(int num)
{        
    int i = num;

    while (i > 2)
    {
        i -= 2;
    }

    if ( i == 1 )
    {
        return "odd";
    }
    else
    {
        return "even";
    }
}

So, for testing, I added a couple of methods that contain loops. I also added some code to time the execution as well.

Add some variables to hold the elapsedTime:

private static long multiplyElapsedTime = 0;
private static long subtractElapsedTime = 0;

runSubtract:
Note: The following will run 50 iterations.

private static void runSubtract()
{
    long startTime = System.currentTimeMillis();

    for (int i = Integer.MAX_VALUE; i > Integer.MAX_VALUE - 50; i--)
    {
        System.out.println("num: " + i + " " + isOddOrEvenSubtract(i));
    }//for

     long endTime = System.currentTimeMillis();
    subtractElapsedTime = endTime - startTime;

    //System.out.println("Elapsed time (subtraction): " + subtractTotalTime);

    //test with negative numbers
    for (int i = 0; i > -10; i--)
    {
        System.out.println("num: " + i + " " + isOddOrEvenSubtract(i));
    }//for
} 

runMultiply:
Note: The following will run 1,000 iterations.

private static void runMultiply()
{
    System.out.println();

    long startTime = System.currentTimeMillis();

    for (int i = Integer.MAX_VALUE; i > Integer.MAX_VALUE - 1000; i--)
    {
        System.out.println("num: " + i + " " + isOddOrEvenMultiply(i));
    }//for

    long endTime = System.currentTimeMillis();
    multiplyElapsedTime = endTime - startTime;

    //System.out.println("Elapsed time (multiply): " + multiplyTotalTime);

    //test with negative numbers
    for (int i = 0; i > -10; i--)
    {
        System.out.println("num: " + i + " " + isOddOrEvenMultiply(i));
    }//for 
}

Usage:

runSubtract();
runMultiply();

System.out.println("Elapsed time (subtraction): " + subtractElapsedTime);
System.out.println("Elapsed time (multiply): " + multiplyElapsedTime);

Results:

  • Elapsed time (subtraction): 30317 -- this was for 50 iterations
  • Elapsed time (multiply): 93 -- this was for 1,000 iterations

I know that some people like to write short code, but short code isn't always fast code.

Yup. The multiply version is the same as the shift version, obviously the fastest and cleanest way to do it. The subtraction thing is just for fun :)

Interesting ..

Thanks to all the people who contributed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.