Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Terse Code for Odd Numbers

by Animator (Hermit)
on May 13, 2005 at 20:06 UTC ( [id://456877]=note: print w/replies, xml ) Need Help??


in reply to Terse Code for Odd Numbers

Another possibility: print grep { $_ & 1 } 1 .. 13

Update For those who need the explenation: read the next node :)

Replies are listed 'Best First'.
Re^2: Terse Code for Odd Numbers
by deep submerge (Scribe) on May 13, 2005 at 20:29 UTC

    This is just for my or for future readers' reference... Please correct me if there's anything wrong or not explained properly. One reason I type this out is because I see code examples that use voodoo I'm not yet accustomed to. So maybe I can help someone else that reads this in the future. =)

    The expression $_ & 1 will evaluate to zero (false) for any even number $_. This uses the bitwise operator &...

    Translate both numbers ($_ and 1) to their binary formats and fill the lesser number with leading zeros (13 => 1101, 1 => 0001)... Perform the AND comparison between the numbers vertically and return that result. Since 1 is a number with many leading zeros, it cancels/falses out all higher order bits greater than 1 for the first number. The only way to make this expression true is to compare the two first bits as 1 AND 1. 1 is an active bit in binary when the first number is odd.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://456877]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (2)
As of 2024-04-19 19:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found