DIGIT-ARC read-only archive · snapshot: July 23, 2026

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

27 posts · originally from https://geek.digit.in/community/threads/tricky-method-find-whether-a-number-is-odd-or-even.84937/

gary4gar
gary4gar Original post #1
Apr 10, 2008 at 10:21 AM
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 at 10:26 AM
Isnt the best method but works;

Code:
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 at 10:52 AM
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
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;
}
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
even number
even number
ray|raven
Apr 10, 2008 at 11:00 AM
Dude, you forgot the semi-colon at the end of the for.
Here's the C code

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 at 11:28 AM
Thanks, it worked;)
M
Apr 10, 2008 at 12:02 PM
How about this
Code:
#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 at 12:06 PM
Binary operators, now why didnt i think of that.

Btw, nice work mehul.
QwertyManiac
Apr 10, 2008 at 1:56 PM
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 at 2:23 PM
Thank You!, Mehul
dheeraj_kumar
Apr 14, 2008 at 8:08 PM
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
Code:
while (num > 1)
      num >>= 1;
if (num == 1)
      print "odd"
else
      print "even"
M
mehulved #11
Apr 14, 2008 at 9:17 PM
More ways? This is fun for noobs like me.
QwertyManiac
Apr 14, 2008 at 9:28 PM
Right shifting by one number returns the integer division by 2. It can't tell you if its even or odd..
M
mehulved #13
Apr 14, 2008 at 9:30 PM
OK. That didn't work.
dheeraj_kumar
Apr 15, 2008 at 4:32 AM
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 at 8:20 AM
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 at 8:20 AM
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:

Code:
>>> 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:

Code:
#!/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
"""
M
mehulved #17
Apr 15, 2008 at 8:25 AM
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
ray|raven #18
Apr 15, 2008 at 8:26 AM
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 at 8:36 AM
Err, getting the last digit in C is as easy as indexing it to sizeof()-1 ?
victor_rambo
Apr 15, 2008 at 9:04 AM
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:
<?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";
}
?>
M
mehulved #21
Apr 15, 2008 at 9:09 AM
Err, getting the last digit in C is as easy as indexing it to sizeof()-1 ?
All right.

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
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:
<?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";
}
?>

Wouldn't using case be better instead of if?
victor_rambo
Apr 15, 2008 at 9:15 AM
Wouldn't using case be better instead of if?
Ya, you could use switch() too.
PHP:
$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.
PHP:
$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
aadipa #23
Apr 15, 2008 at 11:27 AM
How about this
Code:
#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);
}
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()
Code:
    if(num&1)
        printf("%d is odd", num\n);
    else
        printf("%d is even", num\n);
dheeraj_kumar
Apr 15, 2008 at 2:53 PM
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 at 3:17 PM
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()
Code:
    if(num&1)
        printf("%d is odd", num\n);
    else
        printf("%d is even", num\n);
But doesn't the comparison of jump-if-not-zero happen anyway?
aadipa
aadipa #26
Apr 15, 2008 at 3:36 PM
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.

But doesn't the comparison of jump-if-not-zero happen anyway?
Code:
if(num&1)
Code:
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 at 7:54 PM
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.