CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Odds & Evens

 



Pro_4
User

Jun 1, 2001, 7:44 PM

Post #1 of 4 (658 views)
Odds & Evens Can't Post

Hey,

I was wondering how do you tell if a number is odd or even. It would be set up kinda like this:

Code
$number= "31"; 
if ($number is odd) { do this
} else {
do this (it will have to be even)
}

I guess you could feed all the odd numbers you need into a array but that wouldnt be really practical and wouldnt work in my case since the number might be 1001 or something. Is there any built in function that can do this easily?

Thanks :)

Yes i am a palm tree. What are you plantist or something!?


Mortimer
journeyman

Jun 1, 2001, 8:31 PM

Post #2 of 4 (654 views)
Re: Odds & Evens [In reply to] Can't Post

You can use the modulus operator...


Code
if( ( $number % 2 ) != 0 ){ 
print "even
";
}
else{
print "odd
";
}

Cheers,
Dave.
www.dmscripts.com
davemortimer@bigpond.com




freddo
User

Jun 2, 2001, 5:04 AM

Post #3 of 4 (643 views)
Re: Odds & Evens [In reply to] Can't Post

Mortimer is very right,

it's a little trick that was used (once upon a time...) when computers where only handling integers (and they just still do, except for the fpu), what was used in assembly is something that looks like that in perl:

Code
#!/usr/bin/perl 

$num = 1234;
print "$num is ", even($num)?"even":"odd", "\n";

$num = 5;
print "$num is ", even($num)?"even":"odd", "\n";

sub even {
$y = $x = shift;
$y >>= 1;
$y <<= 1;
$y == $x;
}

souvenirs, souvenirs...

freddo

;---
Real programmers´butcher dont understand when they just ask for 3735928559.


Mortimer
journeyman

Jun 2, 2001, 7:31 PM

Post #4 of 4 (629 views)
Re: Odds & Evens [In reply to] Can't Post

Luvly work freddo! And isn't it odd that we can even...


Code
my $num = 0.65; 

print even( $num-- ) ? "$num - even< br>" : "$num - odd< br>" for -20..20;

sub even{
my $y = my $x = shift;
$y >>= 1;
$y * 2 ^ $x;
}

...which still goes for the integers, but I do like having my fractions and negative numbers too ;)

Cheers,
Dave.
www.dmscripts.com
davemortimer@bigpond.com
Son: I'm going to become a dot com millionaire.
Father: Don't you need a good idea first?
Son: That *is* the good idea.
(Source: British comedy show).



 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives