Forum     

Go Back   Digit Technology Discussion Forum > Software > Programming
Register FAQ Calendar Mark Forums Read

Programming The destination for developers - C, C++, Java, Python and the lot


Closed Thread
 
LinkBack Thread Tools Display Modes
Old 10-04-2008, 10:21 AM   #1 (permalink)
GaurishSharma.com
 
gary4gar's Avatar
 
Join Date: May 2005
Location: Jaipur
Posts: 4,116
Lightbulb [tricky method] Find whether a number is odd or even.


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 ?
gary4gar is offline  
Advertisements. Register and be a member of the community to get rid of them.
Advertisement

Old 10-04-2008, 10:26 AM   #2 (permalink)
Think Zen.
 
ray|raven's Avatar
 
Join Date: Dec 2005
Posts: 1,498
Default Re: [tricky method] Find whether a number is odd or even.

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.
__________________
Do what you will; but not because you must. -- Zen Quote
ray|raven is offline  
Old 10-04-2008, 10:52 AM   #3 (permalink)
GaurishSharma.com
 
gary4gar's Avatar
 
Join Date: May 2005
Location: Jaipur
Posts: 4,116
Default Re: [tricky method] Find whether a number is odd or even.

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

Quote:
Please Enter the Number You wish to check
?9
even number
even number
even number
even number

Last edited by gary4gar; 10-04-2008 at 11:27 AM.
gary4gar is offline  
Old 10-04-2008, 11:00 AM   #4 (permalink)
Think Zen.
 
ray|raven's Avatar
 
Join Date: Dec 2005
Posts: 1,498
Default Re: [tricky method] Find whether a number is odd or even.

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;
}
__________________
Do what you will; but not because you must. -- Zen Quote
ray|raven is offline  
Old 10-04-2008, 11:28 AM   #5 (permalink)
GaurishSharma.com
 
gary4gar's Avatar
 
Join Date: May 2005
Location: Jaipur
Posts: 4,116
Default Re: [tricky method] Find whether a number is odd or even.

Thanks, it worked
gary4gar is offline  
Old 10-04-2008, 12:02 PM   #6 (permalink)
18 Till I Die............
 
Join Date: Jul 2004
Location: India, Mumbai, Marine Lines
Posts: 5,792
Default Re: [tricky method] Find whether a number is odd or even.

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);
}
__________________
http://www.bash.org/?258908
mehulved is offline  
Old 10-04-2008, 12:06 PM   #7 (permalink)
Think Zen.
 
ray|raven's Avatar
 
Join Date: Dec 2005
Posts: 1,498
Default Re: [tricky method] Find whether a number is odd or even.

Binary operators, now why didnt i think of that.

Btw, nice work mehul.
__________________
Do what you will; but not because you must. -- Zen Quote
ray|raven is offline  
Old 10-04-2008, 01:56 PM   #8 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: [tricky method] Find whether a number is odd or even.

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.
__________________
Harsh J
www.harshj.com
QwertyManiac is offline  
Old 10-04-2008, 02:23 PM   #9 (permalink)
GaurishSharma.com
 
gary4gar's Avatar
 
Join Date: May 2005
Location: Jaipur
Posts: 4,116
Default Re: [tricky method] Find whether a number is odd or even.

Thank You!, Mehul
gary4gar is offline  
Old 14-04-2008, 08:08 PM   #10 (permalink)
Legen-wait for it-dary!
 
dheeraj_kumar's Avatar
 
Join Date: Dec 2004
Location: Chennai
Posts: 2,471
Default Re: [tricky method] Find whether a number is odd or even.

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"
__________________
If the Start Windows Restart when Windows starts check box is checked Windows Restart will start automatically every time Windows is started. - Actual excerpt from a windows program help file
dheeraj_kumar is offline  
Old 14-04-2008, 09:17 PM   #11 (permalink)
18 Till I Die............
 
Join Date: Jul 2004
Location: India, Mumbai, Marine Lines
Posts: 5,792
Default Re: [tricky method] Find whether a number is odd or even.

More ways? This is fun for noobs like me.
__________________
http://www.bash.org/?258908
mehulved is offline  
Old 14-04-2008, 09:28 PM   #12 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: [tricky method] Find whether a number is odd or even.

Right shifting by one number returns the integer division by 2. It can't tell you if its even or odd..
__________________
Harsh J
www.harshj.com
QwertyManiac is offline  
Old 14-04-2008, 09:30 PM   #13 (permalink)
18 Till I Die............
 
Join Date: Jul 2004
Location: India, Mumbai, Marine Lines
Posts: 5,792
Default Re: [tricky method] Find whether a number is odd or even.

OK. That didn't work.
__________________
http://www.bash.org/?258908
mehulved is offline  
Old 15-04-2008, 04:32 AM   #14 (permalink)
Legen-wait for it-dary!
 
dheeraj_kumar's Avatar
 
Join Date: Dec 2004
Location: Chennai
Posts: 2,471
Default Re: [tricky method] Find whether a number is odd or even.

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?
__________________
If the Start Windows Restart when Windows starts check box is checked Windows Restart will start automatically every time Windows is started. - Actual excerpt from a windows program help file
dheeraj_kumar is offline  
Old 15-04-2008, 08:20 AM   #15 (permalink)
हॉर्न ओके प्लीज़
 
victor_rambo's Avatar
 
Join Date: Sep 2007
Posts: 1,493
Default Re: [tricky method] Find whether a number is odd or even.

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.
__________________
विक्टर रॅंबो - चाणकया प्रभावित व्यक्ति

गीक होना माँगता
victor_rambo is offline  
Old 15-04-2008, 08:20 AM   #16 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: [tricky method] Find whether a number is odd or even.

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
"""
__________________
Harsh J
www.harshj.com

Last edited by QwertyManiac; 15-04-2008 at 08:34 AM.
QwertyManiac is offline  
Old 15-04-2008, 08:25 AM   #17 (permalink)
18 Till I Die............
 
Join Date: Jul 2004
Location: India, Mumbai, Marine Lines
Posts: 5,792
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by rohan_shenoy View Post
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?
__________________
http://www.bash.org/?258908
mehulved is offline  
Old 15-04-2008, 08:26 AM   #18 (permalink)
Think Zen.
 
ray|raven's Avatar
 
Join Date: Dec 2005
Posts: 1,498
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by rohan_shenoy View Post
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.
__________________
Do what you will; but not because you must. -- Zen Quote
ray|raven is offline  
Old 15-04-2008, 08:36 AM   #19 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: [tricky method] Find whether a number is odd or even.

Err, getting the last digit in C is as easy as indexing it to sizeof()-1 ?
__________________
Harsh J
www.harshj.com
QwertyManiac is offline  
Old 15-04-2008, 09:04 AM   #20 (permalink)
हॉर्न ओके प्लीज़
 
victor_rambo's Avatar
 
Join Date: Sep 2007
Posts: 1,493
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by mehulved View Post
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 Code:
<?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";
}
?>
__________________
विक्टर रॅंबो - चाणकया प्रभावित व्यक्ति

गीक होना माँगता

Last edited by victor_rambo; 15-04-2008 at 09:05 AM. Reason: Automerged Doublepost
victor_rambo is offline  
Old 15-04-2008, 09:09 AM   #21 (permalink)
18 Till I Die............
 
Join Date: Jul 2004
Location: India, Mumbai, Marine Lines
Posts: 5,792
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by QwertyManiac View Post
Err, getting the last digit in C is as easy as indexing it to sizeof()-1 ?
All right.

Quote:
Originally Posted by rohan_shenoy View Post
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
Quote:
Originally Posted by rohan_shenoy View Post
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 Code:
<?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?
__________________
http://www.bash.org/?258908

Last edited by mehulved; 15-04-2008 at 09:09 AM. Reason: Automerged Doublepost
mehulved is offline  
Old 15-04-2008, 09:15 AM   #22 (permalink)
हॉर्न ओके प्लीज़
 
victor_rambo's Avatar
 
Join Date: Sep 2007
Posts: 1,493
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by mehulved View Post
Wouldn't using case be better instead of if?
Ya, you could use switch() too.
PHP Code:
$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 Code:
$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";

__________________
विक्टर रॅंबो - चाणकया प्रभावित व्यक्ति

गीक होना माँगता
victor_rambo is offline  
Old 15-04-2008, 11:27 AM   #23 (permalink)
Wise Old Owl
 
aadipa's Avatar
 
Join Date: Feb 2004
Location: Palghar, Mumbai
Posts: 1,000
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by mehulved View Post
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);
__________________
i generally prefer quality over quantity
1 aadi + 1 aadi = 1 full ;)
aadipa is offline  
Old 15-04-2008, 02:53 PM   #24 (permalink)
Legen-wait for it-dary!
 
dheeraj_kumar's Avatar
 
Join Date: Dec 2004
Location: Chennai
Posts: 2,471
Default Re: [tricky method] Find whether a number is odd or even.

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.
__________________
If the Start Windows Restart when Windows starts check box is checked Windows Restart will start automatically every time Windows is started. - Actual excerpt from a windows program help file
dheeraj_kumar is offline  
Old 15-04-2008, 03:17 PM   #25 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by aadipa View Post
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?
__________________
Harsh J
www.harshj.com
QwertyManiac is offline  
Old 15-04-2008, 03:36 PM   #26 (permalink)
Wise Old Owl
 
aadipa's Avatar
 
Join Date: Feb 2004
Location: Palghar, Mumbai
Posts: 1,000
Default Re: [tricky method] Find whether a number is odd or even.

Quote:
Originally Posted by dheeraj_kumar View Post
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.

Quote:
Originally Posted by QwertyManiac View Post
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.
__________________
i generally prefer quality over quantity
1 aadi + 1 aadi = 1 full ;)

Last edited by aadipa; 15-04-2008 at 03:36 PM. Reason: Automerged Doublepost
aadipa is offline  
Old 15-04-2008, 07:54 PM   #27 (permalink)
Legen-wait for it-dary!
 
dheeraj_kumar's Avatar
 
Join Date: Dec 2004
Location: Chennai
Posts: 2,471
Default Re: [tricky method] Find whether a number is odd or even.

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.
__________________
If the Start Windows Restart when Windows starts check box is checked Windows Restart will start automatically every time Windows is started. - Actual excerpt from a windows program help file
dheeraj_kumar is offline  
Closed Thread

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Shell script to find whether number is prime or not preshit.net Programming 6 21-02-2008 06:26 PM
How To Find Total Number of Websites? muralikrishnan QnA (read only) 5 21-06-2006 12:46 PM
Code to find Number of command buttons sid_b6505 QnA (read only) 3 06-12-2005 06:19 PM
Code to find number of command buttons sid_b6505 Tutorials 1 04-12-2005 09:34 PM
How to find phone number of a friend in yahoo messenger robogeek Mobiles and Tablets 2 17-11-2005 09:47 PM

 
Latest Threads
- by Sujeet
- by clmlbx
- by Sujeet
- by icebags

Advertisement




All times are GMT +5.5. The time now is 10:57 AM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2012, vBulletin Solutions, Inc.

Search Engine Optimization by vBSEO 3.3.2