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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
This weeks puzzler from CarTalk (not a permalink. week 11/17/2005) inspired me to verify my solution by writing a short Perl script. The puzzle is stated like so:
The Hall of 20,000 Ceiling Lights

There are 20,000 lights on. A person comes through and pulls the cord on every second light. A third person comes along and pulls the cord on every third light, etc. When someone comes who pulls every 20,000th chain, which lights are on?

Can you solve the puzzle? Without a script?

My script looks like so:

use strict; my $MAX = 20001; my @bulbs; $bulbs[$_] = 0 for ( 0..$MAX ); # use 1 and 0 for display purposes # Try goes thru the integers, Switching the bulbs. TRY: for my $try ( 1..$MAX ) { # switch by multiples; MULTIPLE: for my $i ( 1..$MAX ) { my $m = $i*$try; next TRY if ( $m > $MAX ); # a not works nicely here # if you don't plan to print your array $bulbs[$m] = $bulbs[$m] == 1 ? 0 : 1; } } print "\n\n"; for my $n ( 1..$MAX ) { printf "Bulb %5d is ON\n", $n if ( $bulbs[$n] ); }
And the answer is: only bulbs whose numbers are perfect squares are lit. 1,4,9,16...

-------------------------------------
Nothing is too wonderful to be true
-- Michael Faraday


In reply to CarTalk Puzzler by freddo411

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-20 01:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found