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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.