# [tricky method] Find whether a number is odd or even.



## gary4gar (Apr 10, 2008)

I ask you how to Find whether a number is odd or even. you woudl say what a big deal.
its a easy question but the catch is

Conditions :-

Not to use Division Operator (/), Multiplication Operator (*) and Modulous Operator (%)/
 We can use Addition Operator (+) and Substraction Operator (-)


now How it can be done with the above conditions ?


----------



## ray|raven (Apr 10, 2008)

Isnt the best method but works;


```
public class TrickyOdd
{
    public static void main(String args[])
    {
        int number; //Number to be determined as odd or even
        
        for(;number>1;number=number-2);
        if(number==1)
            System.out.println("Odd");
        else
            System.out.println("Even");
    }
}
```

Code's in Java btw.


----------



## gary4gar (Apr 10, 2008)

Thanks for a super quick reply but what language is it?
JAVA?

But yeah i did understand the logic part somewhat.

Here is a C version of it. which i tried to make

```
#include<stdio.h>
int main()
{
	int number;
	printf("Please Enter the Number You wish to check\n");
	scanf("%d", &number);
	for(;number>1;number-=2);
	{
		if(number == 1)
 
			printf("Odd number");
		else
			printf("even number");
 
	}
	return 0;
}
```
But the problem is i get print multiple times.
here what i get when i run it



> Please Enter the Number You wish to check
> ?9
> even number
> even number
> ...


----------



## ray|raven (Apr 10, 2008)

Dude, you forgot the semi-colon at the end of the for.
Here's the C code


```
#include<stdio.h>
int main()
{
    int number;
    printf("Please Enter the Number You wish to check\n");
    scanf("%d", &number);
    for(;number>1;number-=2);
        if(number == 1)
            printf("Odd number");
        else
            printf("even number");
 
    }
    return 0;
}
```


----------



## gary4gar (Apr 10, 2008)

Thanks, it worked


----------



## mehulved (Apr 10, 2008)

How about this

```
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
	int num;

	printf("Please Enter a Number > ");
	scanf("%d", &num);

	if((num&1)==1)
		printf("%d is odd", num\n);
	else
		printf("%d is even", num\n);
	
	return 0;
	exit(0);
}
```


----------



## ray|raven (Apr 10, 2008)

Binary operators, now why didnt i think of that.

Btw, nice work mehul.


----------



## QwertyManiac (Apr 10, 2008)

Yep since all odd numbers have their 2^0th bit set (Even + 1 = Odd) you can simply AND it with 1 to find if its even or odd.


----------



## gary4gar (Apr 10, 2008)

Thank You!, Mehul


----------



## dheeraj_kumar (Apr 14, 2008)

I think you can do something with the shift left and shift right operators << and >>. I did something of that sort at school, now I dont remember. 

something like

```
while (num > 1)
      num >>= 1;
if (num == 1)
      print "odd"
else
      print "even"
```


----------



## mehulved (Apr 14, 2008)

More ways? This is fun for noobs like me.


----------



## QwertyManiac (Apr 14, 2008)

Right shifting by one number returns the integer division by 2. It can't tell you if its even or odd..


----------



## mehulved (Apr 14, 2008)

OK. That didn't work.


----------



## dheeraj_kumar (Apr 15, 2008)

Hmm... I remember doing this with >> very well. and yeah, all it does is divide by 2. The topic started asked us not to use / operator so I did like this.

while (number > 1)
divide by 2 continuously. using shift right.

when the loop stops, it means the number now should be 1 or 0.
1 means there is a remainder. even. 
0 means there isnt.odd.

perhaps my coding was wrong, but the logic sounds ok, doesnt it?


----------



## victor_rambo (Apr 15, 2008)

Ok here is my logic:
1. Get the input
2. Get the last digit of the input
3. Compare if last digit is any of these: 0, 2, 4, 6 and 8.


----------



## QwertyManiac (Apr 15, 2008)

Very wrong. As you see, the division by 2 is an Integer division, so all that you get in the end would be == 1.

Besides, how are you gonna find the remainder without having to use the divmod or mod operations. Could you show it in some implementation?

Using your logic for 'variable' remainders, if thats what you meant, here's the try out:


```
>>> def div(x):
...     while x>1:
...             x>>=1
...     return x
... 
>>> for x in range(1,50): 
...     print div(x)
... 
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
```

You can see it, all kinds of numbers will only return 1.

Ps. Good try Rohan, but I bet its efficiency is very low. Let's check:


```
#!/usr/bin/env python

import time

def str_method(x):
	x=str(x)[-1]
	s=set('02468')
	if x in s:
		return 0
	else:
		return 1

def bin_method(x):
	if x & 1:
		return 1
	else:
		return 0

m=time.time()
map(bin_method,xrange(0,1000))
print time.time()-m

m=time.time()
map(str_method,xrange(0,1000))
print time.time()-m

"""
Tries:
Q@Q ~ $ python test.py
0.000995874404907
0.0157248973846
Q@Q ~ $ python test.py
0.000957012176514
0.0170290470123
"""
```


----------



## mehulved (Apr 15, 2008)

rohan_shenoy said:


> Ok here is my logic:
> 1. Get the input
> 2. Get the last digit of the input
> 3. Compare if last digit is any of these: 0, 2, 4, 6 and 8.


How will we get the last digit without using modulus?


----------



## ray|raven (Apr 15, 2008)

rohan_shenoy said:


> Ok here is my logic:
> 1. Get the input
> 2. Get the last digit of the input
> 3. Compare if last digit is any of these: 0, 2, 4, 6 and 8.



IMO, that would complicate the code.
So far, Mehul's is the simplest.


----------



## QwertyManiac (Apr 15, 2008)

Err, getting the last digit in C is as easy as indexing it to sizeof()-1 ?


----------



## victor_rambo (Apr 15, 2008)

mehulved said:


> How will we get the last digit without using modulus?


I don't think that should be difficult. In PHP, there is a function for this. Since PHP syntax is derived from C, I am sure there must be a similar function in C too.

Ok, here is the PHP code to do it. As I said, there is an inbuilt function to get a substring out from a string.

```
<?php
$input="12345";//input number
$last_digit=substr($input,"-1");//get the last digit
if($last_digit=="0" || 
$last_digit=="2" || 
$last_digit=="4" || 
$last_digit=="6" || 
$last_digit=="8")
//compare the last digit to see if its either of 0, 2, 4, 6 or 8, or use in_array() function.
{
print "Input is an even number";
}
else
{
print "Input is an odd number";
}
?>
```


----------



## mehulved (Apr 15, 2008)

QwertyManiac said:


> Err, getting the last digit in C is as easy as indexing it to sizeof()-1 ?


All right.



rohan_shenoy said:


> I don't think that should be difficult. In PHP, there is a function for this. Since PHP syntax is derived from C, I am sure there must be a similar function in C too.


Yes, but I needed info on how to do it. QwertyM has replied to that now


rohan_shenoy said:


> Ok, here is the PHP code to do it. As I said, there is an inbuilt function to get a substring out from a string.
> 
> ```
> <?php
> ...



Wouldn't using case be better instead of if?


----------



## victor_rambo (Apr 15, 2008)

mehulved said:


> Wouldn't using case be better instead of if?


Ya, you could use switch() too.

```
$input="12345";//input number
$last_digit=substr($input,"-1");//get the last digit
switch($last_digit)
{
case 0; case 2; case 4; case 6; case 8;
print "Number is even";
break;

default;
print "Number is odd";
}
```

Also you can do it by using array functions:
1. Create an array containing even numbers.
2. check if the last digit is exists in the array.
3. If it exists->Number is even; Else:->Number is odd.

```
$input="12345";//input number
$last_digit=substr($input,"-1");//get the last digit
$array_of_even_numbers=array("0","2","4","6","8");
if(in_array($last_digit,$array_of_even_numbers))
{
print "Number is even";
}
else
{
print "Number is odd";
}
```


----------



## aadipa (Apr 15, 2008)

mehulved said:


> How about this
> 
> ```
> #include <stdio.h>
> ...


Just a small modification to Mehul's code which is best and most efficient solution to the problem.
In C, any non-zero value is true, only zero is false. So we can skip comparison in if()

```
if(num&1)
        printf("%d is odd", num\n);
    else
        printf("%d is even", num\n);
```


----------



## dheeraj_kumar (Apr 15, 2008)

How about sprintf function?

char* str;
sprintf(str, "%d", number);
printf("%c", str[strlen(str)-1]);

we can also use itoa instead of sprintf, i guess.


----------



## QwertyManiac (Apr 15, 2008)

aadipa said:


> Just a small modification to Mehul's code which is best and most efficient solution to the problem.
> In C, any non-zero value is true, only zero is false. So we can skip comparison in if()
> 
> ```
> ...


But doesn't the comparison of jump-if-not-zero happen anyway?


----------



## aadipa (Apr 15, 2008)

dheeraj_kumar said:


> How about sprintf function?
> char* str;
> sprintf(str, "%d", number);
> printf("%c", str[strlen(str)-1]);
> we can also use itoa instead of sprintf, i guess.


Wont it just print last digit of number? We need to find whether number is even or odd.



QwertyManiac said:


> But doesn't the comparison of jump-if-not-zero happen anyway?




```
if(num&1)
```


```
if((num&1)==1)
```
2nd code has 1 more comparision before result is fed to if condition. this will add 1 more instruction, hence will perform slower.


----------



## dheeraj_kumar (Apr 15, 2008)

Oh, I'm sorry, I meant to combine it with rohan's idea. If the last digit is 0,2,4,6,8 then its even. Or else, its odd.


----------

