Monday, November 06, 2006

Frid....err...Monday math solution

The answer to last week's "Lockers" problem: only perfect squares stay open. This can be seen with experimentation. The reason why this is true is due to parity - the number of divisors of n is odd iff n is a perfect square.

Daniel, of course, saw this as an exercise in programming, and wrote a Perl script.

#!/usr/bin/perl
use strict;
use warnings;
my $CLOSED = q{.};
my $OPENED = q{O};
my $NUM_LOCKERS = 80;
my %lockers;
# Set all the lockers to be cloesd
map { $lockers{$_} = $CLOSED } 1 .. $NUM_LOCKERS;
for my $n ( 2 .. $NUM_LOCKERS ){
for my $i ( $n .. $NUM_LOCKERS ) {
# Every nth locked => divisible by n
if ( $i % $n == 0 ) {
# Toggle the state of the locker
$lockers{$i} = $lockers{$i} eq $OPENED ? $CLOSED : $OPENED;
}
}
print "$n:\t", join ( q{}, @lockers{1..$NUM_LOCKERS} ), "\n";
}

I didn't get a chance to blog this on Friday, on account of my having a life. Sorry. The weekly math problem is turning out to be too much of a commitment, it seems (regardless of how helpful these may prove during the occasional job interview). I'll post problems as they come up, but I don't think that I can keep to a schedule.

4 Comments:

At 11/06/2006 11:06 PM, selfish crab said...

I'm going to make Ben into a big ol' jock.

Wouldn't that be the height of hilarity? All your riddles and Perl programs would be lost on him. How tragic.

sincerely,
Loki

 
At 11/07/2006 12:38 AM, Zach said...

Er, what's the point of defining all these constants in a fifteen-line program? Man! $CLOSED?

Time to teach Perl class!

 
At 11/07/2006 10:05 AM, Anonymous said...

aw i hope you post them frequently. i used this one in a class - gave it as an extra credit on one of the homeworks and the kids loved it. keep them coming!

 
At 11/07/2006 10:06 AM, Irina said...

What do you know about being a jock anyway? Fantasy hockey doesn't exactly involve serious physical ability! Not like... uh... chess! Or, Starcraft!

 

Post a Comment

<< Home