Showing posts with label math. Show all posts
Showing posts with label math. Show all posts

Monday, October 09, 2017

Well, that’s weird: Fibonacci edition

About six years ago, I read a puzzle about Fibonacci numbers in CACM and tried to understand the solution, so when I recently saw on quora the question “Is every Fibonacci number divisible by 31 also divisible by 61?” I was interested enough to figure out (to my surprise) that indeed every one is: every 15th Fibonacci number is divisible by 61, but only every 30th is divisible by 31.

This I found unusual and amazing, and I wondered, for what other primes is this true? Naturally I wrote some Python.

#!/usr/bin/python -utt
# vim:et:sw=4

'''
Let f(n) be the nth Fibonacci number (f(0)=0, f(1)=1, f(n)=f(n-1)+f(n-2))
For prime p, let ff(p) be the smallest n such that p|f(n),
e.g. ff(3)=4 because f(4)=3

Now, what primes (p, p2) satisfy p>p2 but ff(p)<ff(p2) and ff(p)|ff(p2)?
'''
import sys

def main(maxx):
    '''
    Get primes up to /maxx/, and the first /maxx/ Fibonacci numbers,
    then check for the criteria described above.
    '''
    plist = prime_list(maxx)
    flist = fib_list(maxx)
    ff = dict()
    for p in plist:
        for n, f in enumerate(flist):
            if f >= p and f % p == 0:
               ff[p] = n        # e.g. since f(4) == 3, ff[3] = 4
               break
        else:
            print "Couldn't find fib which %d divides" % (p)
    # Now ff[p] is idx of 1st fib that p divides
    for idx, p in enumerate(plist):
        f = ff[p]
        for j, p2 in enumerate(plist[:idx]):
            # for p2 < p
            f2 = ff[p2]
            if f2 > f and f2 % f == 0:
                print 'f(%d) = %d and f(%d) = %d' % (p, f, p2, f2)
            
    sys.exit(0)

def prime_list(pmax):
    '''
    Return a list of prime numbers up to pmax (sloppy criterion)
    '''
    # First two nontrivial primes
    plist = [2, 3]
    # Look for further primes by formula p = 6k +/- 1 for some k
    for cseed in range(6, pmax, 6):
        cand1, cand2 = cseed - 1, cseed + 1
        for p in plist[2:]:
            # Zero a cand if another prime p>3 divides it.
            # Need not check p≤3 because of construction.
            if cand1 == cand2:
                # must both be zero
                break
            if cand1 and cand1 % p == 0:
                cand1 = 0
            if cand2 and cand2 % p == 0:
                cand2 = 0
        else:
            append_t(plist, cand1)
            append_t(plist, cand2)
    return plist

def append_t(alist, athing):
    '''
    Helper: append /athing/ to /alist/ but only if /athing/ is "true"
    '''
    if athing:
        alist.append(athing)


def fib_list(fmax):
    '''
    Return a list of the first /fmax/ Fibonacci numbers
    '''
    bak1, cur = 0, 1            # f(0)=0, f(1)=1
    flist = [bak1, cur]
    for n in range(2, fmax):
        bak1, cur = cur, cur + bak1
        flist.append(cur)
    assert flist[5] == 5        #print 'DEBUG:', 5, flist[5]
    #print 'DEBUG:', flist
    return flist

if __name__ == '__main__':
    maxx = 99
    if len(sys.argv) > 1:
        maxx = int(sys.argv[1])
    main(maxx)
Running it produces:
Collins-MacBook-Pro:fib31 collin$ ./pfib.py 
f(61) = 15 and f(31) = 30
f(89) = 11 and f(43) = 44
Collins-MacBook-Pro:fib31 collin$ 
Whoa, really? Every 11th prime is divisible by 89, but only every 44th is divisible by 43? H'm.
f(11)=89, f(22)=17711, f(33)=3524578, f(44)=701408733
Every one of those guys is divisible by 89, but only the last is divisible by 43. How weird is that? And from looking at the pattern of what happens to f(n) mod 89 as n increases, it's clear that indeed every 11th Fibonacci number is divisible by 89, and every 44th is divisible by 43.

If instead of 99 we say 199 or 299, what do we get?

Collins-MacBook-Pro:fib31 collin$ ./pfib.py 199
f(61) = 15 and f(31) = 30
f(89) = 11 and f(43) = 44
f(199) = 22 and f(43) = 44
Collins-MacBook-Pro:fib31 collin$ 
OK, I examined that one, and everything is as it seems. What if we go another 100?
Collins-MacBook-Pro:fib31 collin$ ./pfib.py 299
f(61) = 15 and f(31) = 30
f(89) = 11 and f(43) = 44
f(199) = 22 and f(43) = 44
f(211) = 42 and f(83) = 84
f(211) = 42 and f(167) = 168
f(229) = 114 and f(227) = 228
f(233) = 13 and f(79) = 78
f(233) = 13 and f(103) = 104
f(233) = 13 and f(131) = 130
f(281) = 28 and f(83) = 84
f(281) = 28 and f(167) = 168
f(281) = 28 and f(223) = 224
Collins-MacBook-Pro:fib31 collin$ 
Well, that was fun if not exactly insightful. Why so many from 200–299, compared to the range 1–199? But the upshot is, we could ask a number of other questions, like
  • Is every Fibonacci number that's divisible by 89 or 199 also divisible by 43? (Yes.)
  • Is every Fibonacci number that's divisible by 79 or 103 or 131 also divisible by 233? (Yes.)
and so on. No idea why, but there it is.

Thursday, April 16, 2015

A programming surprise

Many years ago, when I was in graduate school and most of my colleagues hadn't even been born yet (!), I took a class on computer architecture. Part of the class involved programming a function/subroutine to compute the nth Fibonacci number in various machines' assembly languages.

Later, when I started interviewing candidates for programming jobs, I would ask them to describe their approach, and then write code to do that computation. I did that for some 25 years or so, but one day, I saw an answer I could not have imagined beforehand. Well, maybe if I had done a lot more reading and thinking about the mathematics of it I might have... Anyway, I wanted to share it with you so I wrote it down here.

Wednesday, February 25, 2015

A high school math problem and Euler's formula

I was on my high school's math team in the early '70s, and in one contest there was a problem that stumped us. Basically it was this:
Find two numbers, not 0 or 1, such that each is the square of the other.
If you remember that there is such a thing as a complex number, the problem isn't hard. Trouble was, we had all forgotten about such things in the moment.

But what happened afterward was very interesting to me. I noticed that the solution involved complex numbers, and a particular kind of complex number: the kind with a "length" or "magnitude" of 1. Somehow I noticed what happens when you multiply such complex numbers together.

It was so much fun learning all that, and I was thinking about it again for some reason recently. So I wrote a bunch of stuff down. Not in blogger; this requires LaTeX. Some topics mentioned:

  • factoring
  • quadratic formula
  • addition formulas for sin and cos
  • matrix multiplication (2x2)
  • Maclaurin series (Taylor series centered at 0) This is the only part needing calculus.
  • "isomorphic" which just means that this thing is like that thing and behaves in the same way. Probably I misuse the word somewhere.
It sure was fun to learn that stuff, and fun to think about it again and write some of it down.

I've uploaded my little paper here.

Thursday, June 20, 2013

But wait, Spot-It! has only 55 cards.

In a previous post and its follow-up I described the process by which I decided that Spot-It! likely used 57 symbols and that it could have up to 57 cards in its deck. But as mentioned earlier, the deck actually has only 55 cards. Did they just leave two cards out? Do they have more symbols, or fewer?

Yes, they just left two cards out; no, they use exactly 57 symbols. To figure this out, I created a file "cards.txt", with the name of each symbol on a single line. The symbols on a given card are grouped together in an eight-line stanza; an empty line separates stanzas.

yin-yang
paint
tree
lightning
zebra
clef
ladybug
Canada

bomb
dragon
carrot
paint
ghost
question
bang
clown

spider
…etc.
The excerpt at right signifies that:
  • one card contains the yin/yang sign, the paint dots, tree, lightning bolt, zebra, (treble) clef, ladybug, maple leaf;
  • another card has the bomb, dragon, carrot, paint, ghost, question mark, exclamation point…
you get the idea.

Alert readers may notice that "cards.txt" has names consisting of only one "word" (by which I mean a contiguous sequence of non-whitespace characters) each, and that some of them don't exctly match my summary. The one-"word" thing makes them easier for shell scripts to process, and I translate these internal names into less-cryptic (I hope) things like "maple leaf" (Canada) or "exclamation point" (bang).

The format of "cards.txt" made for easy error checking, which as it turned out was necessary. (If you're thinking at this point, "How anal!" all I can say is "guilty as charged, yer honor.") It also made for some easy analysis. For example, we learn that although most of the symbols appear on 8 cards each, some don't:

% grep -v '^$' cards.txt | sort | uniq -c | sort -n | head -n16
   6 snowman
   7 Canada
   7 bang
   7 cactus
   7 daisy
   7 dinosaur
   7 dog
   7 eye
   7 ice
   7 ladybug
   7 light-bulb
   7 man
   7 question
   7 skull
   7 stop
   8 anchor
% grep -v '^$' cards.txt | sort | uniq -c | sort -n | tail -n3
   8 web
   8 yin-yang
   8 zebra
% 
The (American) English translation of the above is: only six cards have a snowman. Fourteen symbols (maple leaf, exclamation point, cactus, daisy, etc.) appear on only 7 cards each; the rest appear on 8 cards each. This suggests that two cards could be added to the deck. Each card would have a snowman and 7 of the other symbols. Which symbols? Well, any symbol that would appear with the maple leaf (aka "Canada") on a new card must not already appear with the maple leaf on another card. How to decide that?

It takes a few steps. First, a shell script converts "cards.txt" into another file, "cards-sorted.txt":

% L1=1; while [[ $L1 -lt 490 ]] ; do 
    ((L2=L1+7)); sed -n $L1,${L2}p cards.txt | sort | fmt -w222; 
    ((L1=L1+9)); done | 
    sort > cards-sorted.txt
% 
This takes, e.g., lines 1-8 of "cards.txt", sorts them, and combines them into a single line. Then it takes lines 10-17 (that's eight lines) and does the same with them. Then lines 19-26, and so on.

Each line in "cards-sorted.txt" thus corresponds to a single card, and contains the card's one-word symbol names in alphabetical order. Consequently, cards-sorted.txt starts off like this:

% head cards-sorted.txt 
Canada anchor carrot cheese clock knight stop web
Canada apple bang igloo moon scissors snowflake spider
Canada art balloon bomb drop fire lips skull
Canada bottle candle ghost light-bulb lock pencil sunglasses
Canada car cat clover clown dog ok sun
Canada clef ladybug lightning paint tree yin-yang zebra
Canada dolphin dragon eye hand heart key target
anchor apple art dinosaur dolphin ghost ladybug ok
anchor balloon clown lightning snowman spider sunglasses target
anchor bang car clef daisy key lips lock
% 
Now I'll use "cards-sorted.txt" to see which of those fourteen symbols appear together with "Canada" (maple leaf) on any card:
% f() { grep Canada.*$1 cards-sorted.txt; }
% C=; D=; grep -v '^$' cards.txt |sort | uniq -c | sort -n | grep 7 | 
    while read A B; do 
       echo === $B ===
       if f $B; then C="$C $B"; else D="$D $B"; fi 
       echo C=$C
       echo D=$D
    done
… [much output deleted]
C= bang dog eye ladybug light-bulb skull stop
D= Canada cactus daisy dinosaur ice man question
% 
The "C=" symbols already appear together with "Canada" (maple leaf), so we won't put them on the same card as a maple leaf again. Therefore, I think that the following cards, if added, would "complete" a set of 57 cards:
  • snowman, exclamation point, dog, eye, ladybug, light bulb, skull, STOP!
  • snowman, maple leaf, cactus, daisy, dinosaur, ice cube, man, question mark
I wasn't quite confident in this, so I wrote this brief shell script to check it.
% cat checkit.sh 
#!/bin/sh
# Ensure that for any pair of symbols within $C [or $D], no single card 
# contains both members of the pair.

C="bang dog eye ladybug light-bulb skull stop"
D="Canada cactus daisy dinosaur ice man question"

all_combos() {
    while [[ $# -ge 2 ]] ; do
        first=$1
        shift
        for it in $*; do
            echo checking $first $it ...
            if grep $first cards-sorted.txt | grep $it; then 
                echo ERROR $first $it 
            fi
        done
    done
}

all_combos $C
all_combos $D
% 
A visual inspection of the output revealed that we were indeed checking for "bang" and "dog" together, then "bang" and "eye"... and so on. It did all that without ever printing "ERROR", so I think the list is good.

That sure was fun! But let me check one more time. I'll add the above two cards to the list of sorted cards:

% diff cards-sorted.txt  cards-complete.txt 
55a56,57
> snowman bang dog eye ladybug light-bulb skull stop
> snowman Canada cactus daisy dinosaur ice man question
% 
Then let me ensure that given any pair of symbols on a given card, that that card is the only one containing that pair:
% cat check-complete.sh 
#!/bin/sh
# based on checkit.sh -- for every card in the 
# hypothetical "complete" Spot-It! deck (in "cards-complete.txt"),
# extract every pair of symbols. If both members of the pair appear
# on any other card in the complete deck, then print "ERROR"...
TEMPFILE=/tmp/spot-tmp.$$
all_combos() {
    while [[ $# -ge 2 ]] ; do
        first=$1
        shift
        for it in $*; do
            echo checking $first $it ...
            if grep " $first " $TEMPFILE | grep " $it "; then 
                echo ERROR $first $it 
            fi
        done
    done
}
C=cards-complete.txt 
cat $C | while read X; do
    grep -v "$X" $C | sed -e 's/^/ /' -e 's/$/ /' > $TEMPFILE
    all_combos $X
done
rm -f /tmp/spot-tmp*
% 
The above script, "check-complete.sh", completed without ever saying "ERROR".
% ./check-complete.sh > x
% grep -m5 ERROR x
ERROR Canada igloo
ERROR igloo question
ERROR igloo man
ERROR ice igloo
ERROR cactus igloo
% 
To make sure that it actually works, though, I changed the last card to say "igloo Canada…" rather than the correct "snowman Canada…". The script did in fact catch the error, as you can see at right.

Am I satisfied now? I refer you to the "anal" comment above. (In other words, No.) One more thing: the above check-complete.sh verified that we didn't have any PAIR of symbols in common between any pair of cards. What it didn't do is verify that there was in fact any symbol in common between any pair of cards. That's done by this script:

% cat overlaps.sh
#!/bin/sh
# Confirm that at least one symbol overlaps every card vs every other card.
TEMPFILE=/tmp/spot-tmp.$$

check() {
    # Given two cards ($1, $2), ensure exactly one word is in common.
    if [[ $# -ne 2 ]] ; then
        echo "check() called with wrong # of args"
        exit 1;
    fi
    ACARD="$1"
    BCARD="$2"
    NUM=0
    for asym in $ACARD; do
        for bsym in $BCARD; do
            if [[ $asym == $bsym ]] ; then
                ((NUM=NUM+1))
            fi
        done
    done
    if [[ $NUM -ne 1 ]] ; then
        echo ERROR: card1=$ACARD
        echo ERROR: card2=$BCARD
    fi
}

verify_one() {
    # Handle one card's syms (args) vs the rest of the deck ($TEMPFILE)
    ONE="$*"
    cat $TEMPFILE | while read IT; do
        echo checking $ONE ==vs== $IT
        check "$ONE" "$IT"
    done
}
C=cards-complete.txt 
cat $C | while read X; do
    grep -v "$X" $C | sed -e 's/^/ /' -e 's/$/ /' > $TEMPFILE
    verify_one $X
done
rm -f /tmp/spot-tmp*
% 
This completed without error, but just to make sure, I modified the last card to use nonexistent symbol "snowman2" and re-ran it, yielding:
% ./overlaps.sh > x; grep -m6 ERROR x
ERROR: card1=anchor balloon clown lightning snowman spider sunglasses target
ERROR: card2=snowman2 Canada cactus daisy dinosaur ice man question
ERROR: card1=apple bomb cat hand lock snowman tree web
ERROR: card2=snowman2 Canada cactus daisy dinosaur ice man question
ERROR: card1=art candle carrot key moon snowman sun yin-yang
ERROR: card2=snowman2 Canada cactus daisy dinosaur ice man question
% 
Of course, each pair of cards shown (there are lots more) should have the "snowman" in common. By tweaking the last card, I removed that sharing. So the script works, and the hypothetical deck is correct.

Wednesday, June 19, 2013

More Spot-It! Math

In a previous post, I mentioned some work with pencil and paper that led me to a certain formula. This post adds a some detail, and I hope it'll be easier to follow. As you may recall from that previous post, I use M to refer to the number of symbols on a given card, and N to refer to the number of distinct symbols (or "alphabet") from which the symbols are drawn. So, continuing on, here's my exploration of the puzzle starting with M=3.
1|ABC
2|A
D
F
E
G
3|A
4|B
DF
5|BEG
6|CDG
7|CEF
To approach the problem I decided to list each card's symbols in increasing alphabetical order. Please refer to the table at left. The progression A-B-C, A-D-E, A-F-G is perhaps obvious. What of the B-x-x cards?

After each "B", we take vertical slices of the dotted blue square, the first slice being the D F in the thin black border. The thing to note with the "B"s is that the "F" is directly below the "D" (i.e., it's down one row and zero symbols to the right).

Similarly on card 5, B-E-G, the "G" is directly below the "E" in the dotted-blue square.

Regarding the "C"s: note on card 6, C-D-G, that the G is below and to the right of the D in the dotted blue square. Card 7 (C-E-F) shows the principle (we'll expand on this later) that when "below and to the right" runs off the right-hand edge of the dotted blue square, we simply resume counting from the left-most symbol in the same row within the dotted blue square. Thus card 7's C-E-F.

So for cards matching the pattern B-x-x, the 2nd "x" is directly below (i.e., displaced zero symbols to the right) of the 1st "x". For C-x-x, the 2nd "x" is displaced one symbol to the right of the 1st "x". How did I arrive at this? Trial and error and eventual "success."

This solution is symmetric in that each of the 7 symbols appears on 4 cards; any given pair of symbols appears upon one and only one card. (Wait, does every possible pair of symbols appear on a card? Yes.)

Suppose we have M=4, N=13? Does the pattern above generalize? What will we do with cards D-x-x-x—would each subsequent "x" be one row below and two symbols to the right of its predecessor "x"?

1|ABCD
2|A
E
H
K
FG
I J
L M
3|A
4|A
5|B
EHK
6|BFIL
7|BGJM
8|CEIM
9|CFJK
10|CGHL
11|D E J L
12|DFHM
13|DGIK
In a word, "Yes." As the table at right shows, the B-x-x-x cards take vertical slices (a subsequent "x" is directly below the preceding "x"). The 3rd (4th) symbol in a C-x-x-x card is one symbol down and to the right of the 2nd (3rd) symbol within the dotted blue square, as C-E-I-M. Again, if you'd run off the right-hand end of a row, continue counting from the left, staying within the dotted blue box, as in card 9, C-F-J-K.

In the D-x-x-x cards, symbols are one down and two to the right of their predecessors within the dotted blue square, again resuming counting from the left when we run off the right-hand side of a row: thus D-E-J-L, D-F-H-M, D-G-I-K.

As in the M=3,N=7 case, we have each of the N symbols appearing on M cards each; every possible pair of symbols appearing on one card; every pair of cards having one and only one symbol in common. At least so far, then, the solution generalizes thus:

  1. one card with the first M symbols (e.g., A-B-C-D in the table at right)
  2. M-1 cards, which include the (M-1)×(M-1) blue-dotted square region
  3. (M-1)2 cards (in the table at right, three B-x-x-x cards, three C-x-x-x cards, three D-x-x-x cards). Each set of M-1 cards takes one symbol from each row of the blue-dotted square:
    • the B-x-x-x cards take vertical slices, i.e., each subsequent symbol is zero columns to the right of its predecessor in the previous row;
    • in the C-x-x-x cards, each subsequent "x" comes from one column to the right of its predecessor in the previous row (and if you're about to run off the end, resume counting at the far left of the same row);
    • in the D-x-x-x cards, each subsequent "x" comes from two columns to the right of its predecessor in the previous row (and if you're about to run off the end, resume counting at the far left of the same row);
    • … and so on
    If (M-1) is a prime number, then the above procedure yields M-1 sets of M-1 symbols in the blue-dotted square. Each set of M-1 symbols has one from each row in the blue-dotted square. And each set has at most one symbol in common with any other set. For example, E-H-K and E-I-M have only the "E" in common. And either set has only the "E" in common with E-J-L.
    Exercise: What if the (M-1)×(M-1) square is 4×4? Would the D-x-x-x-x cards run into some kind of trouble? (Answer: Yes. And I haven't figured my way out of it.)
This yields (M(M-1)+1) cards total, and the same number of symbols. As suggested in my snarky "Exercise:" comment, the above solution works unaltered only when M-1 is a prime number—which, fortunately for me, is true when M is 8.

And that is true for Spot-It!—each card has eight symbols (M=8), and the "optimum" value of N is 8*7+1=57 symbols, which allows for a deck of 57 cards. In my "ideal" (symmetric) deck, each of the 57 symbols would appear eight times (i.e., once on each of eight cards).

How does this relate to the actual Spot-It! cards? More on that in a subsequent post.

Saturday, June 15, 2013

A "Spot It!" puzzle

The game of “Spot It!” (blueorangegames.com) provided an entertaining mathematical and programming puzzle, which I have mostly (I think) figured out.

In case you haven't seen it, there's a deck of some 55 cards; on each card are eight stylized figures of various creatures or things: man, dragon, dog, cat, car, daisy, maple leaf, and so on. Any two cards in the deck have one and only one figure in common: cards 1 and 2 might both have a man, cards 2 and 3 might both have a dragon, but then card 1 won't have a dragon; card 3 won't have a man.

This strikes some people as odd. “Really?” they say. “Any two cards have exactly one thing in common?” It is indeed true. Which of course made me wonder: How does that work? If each card has M figures out of an alphabet of N, how many cards can you have?

Naturally, I started with M=2 and came upon this rather simple set of 3 cards with N=3 symbols:

A B  
A   C
  B C
If we have N=4 then one could imagine cards (A,B), (A,C), (A,D), but then what? You can't go (B,C) because that has nothing in common with (A,D). So bumping N from 3→4 actually reduces the number of cards with M=2.

Thus with M=2 there's a sort of optimum value of N, namely 3. What's the optimum value of N for M=3 or M=4? The number of cards might have something to do with the number of combinations of N things taken M at a time, but it doesn't say much about the optimum N for a given M.

After many stabs at this with pencil and paper, I came up with the following lists for M=3 and M=4:

1 |A B C        
2 |A     D E    
3 |A         F G
4 |  B   D   F  
5 |  B     E   G
6 |    C D     G
7 |    C   E F  
 
1 |A B C D                  
2 |A       E F G            
3 |A             H I J      
4 |A                   K L M
5 |  B     E     H     K    
6 |  B       F     I     L  
7 |  B         G     J     M
8 |    C   E       I       M
9 |    C     F       J K    
10 |    C       G H       L  
11 |      D E         J   L  
12 |      D   F   H         M
13 |      D     G   I   K    
The pattern that seems to emerge from this is that we have
1. card with figures {1..M}
2. card with figures {1, M+1..2M-1} (M-1) cards M sets of (M-1) cards
…
M. card with figures {1, (M-1)(M-1)+2..M(M-1)+1}
…
(M-1)(M-1)+2. card with figures {M,M+1} and (M-2) figures from the set {2M..M(M-1)+1} (M-1) cards
…
M(M-1)+1. card with figures {M,2M-1} and (M-2) figures from the set {2M..M(M-1)+1}
…the total being M(M-1)+1 figures in the alphabet, and M(M-1)+1 cards.

I believe the optimal N for a given M is M(M-1)+1; this gives a symmetric (I think) set of cards, with each symbol appearing on M cards. I haven't proven any of this, but I have (of course) written some code that generates a set of these things for the case where M-1 is prime—which is the case for the real Spot It! game (M=8). In particular if M=8 then the optimum N would be 8*7+1=57, and the deck could have 57 cards. Why does the real Spot It! card game have only 55 cards in the deck? You got me.

I'll add a link to the code one of these days but right now I think it's time for bed.
Update: Code is here

Saturday, November 12, 2011

Collin writes a program*

(* Title borrowed from Ron Carlson Writes a Story)
A few times in the past months, someone's commented that they have no idea what it's like to write a computer program, so I've been thinking about a sort of gentle introduction to the fun ("joy" seems a bit overstated) of programming. Then it happened—the puzzler from Car Talk was announced, and I thought it was perfect. So in the next 45 minutes I want to write a program to solve last week's puzzler. It goes more or less like this:
Imagine a very long hall with 20,000 lights hanging from the ceiling, all off. These lights are controlled by a pull-chain: pull it once, the light turns on; pull it again and the light turns off.

Now someone comes through the hall and pulls every single chain. The lights are now all on. Person #2 comes through and pulls every 2nd chain, so that now lights 2, 4, 6, 8 and so on are now off. Person #3 comes through and pulls every 3rd chain, thus changing the state of lights 3, 6, 9, 12 and so on; they turn some lights on and some off. Person #4 comes through and flips lights 4, 8, 12, 16 and so on.

And so on, until person #20,000 comes through and only tugs on the chain of the 20,000th light.

Can you predict which lights will be on, and which will be off?

Now with a pencil and paper you might be able to figure this out in five or ten minutes, but like my first math professor, who spent ten minutes figuring out how to avoid a five-minute calculation, we'll go through the process of writing a little program to show how at least some programmers think.

We'll use the programming language Python here. I briefly considered using something like Ruby or OCaml, so we could go through the experience of learning a new programming language together, but I'm long-winded enough that...

Right. So Python. Here's what we're going to do: We'll create a list representing the state of each light fixture. And rather than forcing the program to do exactly 20,000 hanging lights, we'll provide a parameter to say how many lights there are. The pattern will be obvious with as few as 100 lights, so let's start with that. Here's a first partial whack at it.

# Adjust the following line to be however many lights you want
howevermanylights = 38

# "light_states" represents the states of howevermanylights
# Initialize it to have just some junk in element 0
light_states = ['junk']

# Add the states of however many lights
for a_light in range(howevermanylights):
    light_states.append(True)

# We'll add code here to manipulate the lights' states

# Now show the state of each light

for a_light in light_states[1:]:
    if a_light:
        print '*',
    else:
        print ' ',

print
for a_light in range(howevermanylights):
    # print last digit of a_light
    print (a_light % 10),

print
and if I run the program (which I imaginatively called "ceiling") it does this:
$ python ceiling
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
$ 
(The bold blue text is what I typed in response to my computer's prompt.)

This shows that light #0 is, oops... do you see that? I wanted to show the state of light #1, #2, #3 etc., but for some reason the numbers are 0, 1, 2, etc. I need to fix the digit printed. That last part will now read:

for a_light in range(howevermanylights):
    # print last digit of a_light
    print (a_light+1) % 10,

print
OK, that worked. Why did I have that "bug", or error? (Programmers call their mistakes "bugs"; it sounds so much better to say "I had 5 bugs in my code" than "I made 5 mistakes (or more) in my code.")

Well, actually I put it in on purpose. No, really; I wanted to mention that Python, like Perl, starts its lists with index 0 rather than 1. This is why I wrote above

# Initialize it to have just some junk in element 0
light_states = ['junk']
if light_states has howevermanylights elements in it, they will be numbered 0 up to howevermanylights-1.

Why do Python and Perl (and C and java too) start numbering lists/arrays at 0 rather than 1? Well, it's for convenience. The first ten elements (or "decade" of elements) in an array are numbered 0-9; the second ten are numbered 10-19. So you can tell which "decade" we're in by looking at the tens digit.

This stands in contrast to our system of years, where the first century is years 1-100; the second century is years 101-200... the 20th century is 1901-2000, and so on. See how inconvenient this is? The 21st century started in 2001 (not 2000) so you can't tell just by looking at the top digit. A computer scientist didn't come up with this system for numbering years.

So a list of 5 elements (for example) has its elements numbered 0,1,2,3,4. Similarly range(5) gives 5 numbers -- also numbered 0,1,2,3,4. To wit:

$ python 
Python 2.6.5 (r265:79063, Jul  5 2010, 11:47:21) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> range(5)
[0, 1, 2, 3, 4]
>>> 

Anyway, light_states starts at 0, and we number the ceiling lights starting at 1, so I put some junk into element 0 of the list so element 1 could correspond to ceiling light #1, etc.

OK, now let's put some more code in to deal with persons #2–howevermanylights.

# Adjust the following line to be however many lights you want
howevermanylights = 38

# "light_states" represents the states of howevermanylights
# Initialize it to have just some junk in element 0
light_states = ['junk']

# Add the states of however many lights
for a_light in range(howevermanylights):
    light_states.append(True)

# Code to manipulate the lights' states
# We have person#2 upto and including howevermanylights.

for a_person in range(2, howevermanylights+1):
    # Flip every "a_person"th light:
    for a_light in range(a_person, howevermanylights+1, a_person):
        light_states[a_light] = not light_states[a_light]


# Now show the state of each light

for a_light in light_states[1:]:
    if a_light:
        print '*',
    else:
        print ' ',

print
for a_light in range(howevermanylights):
    # print last digit of a_light
    print (a_light+1) % 10,

print
The new code is shown in this color and basically, um, does what it says -- assigns the variable "a_person" all values from 2 upto and including howevermanylights. And for each such person, flips every "a_person"th light.

When I run the program, it does this:

$ python ceiling
*     *         *             *                 *                     *    
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8
$ 
Right, that's not 100 lights, and I've only printed the last digit of the light number, but lights #1, 4, 9, 16, 25, 36 are left on. (If I make howevermanylights much bigger than 38, then you won't be able to see the result on a single line.)

Time's up and you got the basic idea

OK, the above was 45 minutes' worth, but let me take a little more time to do two things:
  • First, let's change this line to say 1000 instead:
    howevermanylights = 1000
  • And let's just list out which lights are on, rather than printing out the state of all the lights:
    # Now show the state of each light
    # Don't do that; just list out number of each light that's on
    for a_num in range(1, howevermanylights+1):
        if light_states[a_num]:
            print 'On:', a_num
And when we run it?
$ python ceiling 
On: 1
On: 4
On: 9
On: 16
On: 25
On: 36
On: 49
On: 64
On: 81
On: 100
On: 121
On: 144
On: 169
On: 196
On: 225
On: 256
On: 289
On: 324
On: 361
On: 400
On: 441
On: 484
On: 529
On: 576
On: 625
On: 676
On: 729
On: 784
On: 841
On: 900
On: 961
$ 
Do you see the pattern there? Every number that's a perfect square is left on, but composite numbers are off. Why perfect squares? That's an exercise left to the reader.

Anyway I hope that gives an idea of some of what it means to write a program. Most of what "real programmers" do is quite a bit more complicated, but that ought to give a flavor for at least some of the tasks. I hope that was fun reading for you; it certainly was enjoyable for me to write.

Finishing(??) touches

OK, it's now the next morning and I wanted to sort of finish the program off, and to give you the whole program in one snarf'n'barf-able blob so you can tweak it yourself, if you've got the interest.
#!/usr/bin/python -utt
'''Program to solve cartalk puzzler
http://www.cartalk.com/content/puzzler/transcripts/201144/index.html

Basically this:
    Imagine a very long hall with 20,000 lights hanging from the
    ceiling, all off.  These lights are controlled by a pull-chain:
    pull it once, the light turns on; pull it again and the light
    turns off.

    Now someone comes through the hall and pulls every single chain.
    The lights are now all on.  Person #2 comes through and pulls
    every 2nd chain, so that now lights 2, 4, 6, 8 and so on are
    now off.  Person #3 comes through and pulls every 3rd chain,
    thus changing the state of lights 3, 6, 9, 12 and so on; they
    turn some lights on and some off.  Person #4 comes through and
    flips lights 4, 8, 12, 16 and so on.

    And so on, until person #20,000 comes through and only tugs on
    the chain of the 20,000th light.

    Can you predict which lights will be on, and which will be off?

The program calculates (not predicts) which lights will be on.

Provide the number of lights in a parameter (default 100)'''

import sys

def main(howevermanylights):

    # "light_states" represents the states of howevermanylights
    # Initialize it to have just some junk in element 0
    light_states = ['junk']

    # Add the states of however many lights
    for a_light in range(howevermanylights):
        light_states.append(True)

    # Code to manipulate the lights' states
    # We have person#2 upto and including howevermanylights.

    for a_person in range(2, howevermanylights+1):
        # Flip every "a_person"th light:
        for a_light in range(a_person, howevermanylights+1, a_person):
            light_states[a_light] = not light_states[a_light]


    # Now show the state of each light
    # Don't do that; just list out number of each light that's on
    for a_num in range(1, howevermanylights+1):
        if light_states[a_num]:
            print 'On:', a_num
    sys.exit(0)

if __name__ == '__main__':
    try:
        num_lights = int(sys.argv[1])
    except:
        num_lights = 100
    main(num_lights)
So this does a few things beyond what I had last night:
  1. You can give a parameter and it'll do the calculation for the number of lights provided
    % ./ceiling.py 38
    On: 1
    On: 4
    On: 9
    On: 16
    On: 25
    On: 36
    % ./ceiling.py 100
    On: 1
    On: 4
    On: 9
    On: 16
    On: 25
    On: 36
    On: 49
    On: 64
    On: 81
    On: 100
  2. It's got documentation:
    % pydoc ceiling | cat
    Help on module ceiling:
    
    NAME
        ceiling
    
    FILE
        /Users/collin/to-mail/ceiling.py
    
    DESCRIPTION
        Program to solve cartalk puzzler
        http://www.cartalk.com/content/puzzler/transcripts/201144/index.html
        
        Basically this:
            Imagine a very long hall with 20,000 lights hanging from the
            ceiling, all off.  These lights are controlled by a pull-chain:
    (etc.)
  3. It's easier to debug (google "python debugger" for more info).
  4. It returns a "success!" code so the system thinks the program worked.

Sunday, October 02, 2011

Does every natural number divide some Fibonacci number?

This puzzle came from a recent CACM. The answer, given in the subsequent issue, was "yes", but I had to think about the explanation before I got it. I'll leave a little whitespace here so you can avoid reading the explanation if you want to think about it some first.























Consider the ordered pairs (fn,fn+1) modulo N, where N is the natural number under consideration. There can only be a finite number of unique such pairs—certainly no more than N2 of them. Hence they must cycle at some point. If we set f0=0 and f1=1, that says there must eventually be some M>0 such that fM=0 (mod N) and fM+1=1 (mod N); this condition is sufficient but not necessary for N | fM to be true. Why must we eventually have this condition? Because given fn and fn+1, we can calculate fn-1 -- that is, the process can be run backward and cannot branch. The CACM answer said that the process can run backward ("Yeah, so what?" I thought) but because I'm slow, it didn't occur to me that since it can run backward, and produce a single result, we could not have the case where f0=0,f1=1 and then at some later point have fX,fX+1 (both nonzero), and at some even later point come back to fX,fX+1 and cycle that way without ever hitting (0,1) again.

Right. Next question: Given a number N, how far must you go to find a Fibonacci number that's a multiple of N? I didn't answer that one; instead I took a very short whack at calculating n>0 such that fn≡0 (mod N) and fn+1≡1 (mod N). Of course a computer program was involved (I think this is what happens to lazy math majors; they become programmers). I wrote the following code before I understood the part about "process can run backward", so...

def doit(the_base):
    apair = 0, 1
    b2i = dict()
    for iter in range(99999):             # arbitrary
        if not SILENT:
            print apair,
        if apair in b2i:
            if SILENT:
                return iter, b2i[apair]
            print '\nDone at %d: %s seen at %d' % (
                            iter, `apair`, b2i[apair])
            break
        b2i[apair] = iter
        apair = (apair[1], (apair[0] + apair[1]) % the_base)
    else:
        print "You can't get here --- at least I hope not; base =", the_base
        sys.exit(1)
I ran this for several values of the_base and found what look like some interesting patterns. Now let φ(N) be the smallest n>0 such that fn≡0(mod N), fn+1≡1(mod N). It seems that if N=p1p2, p1≠p2, then φ(N)=LCM(φ(p1),φ(p2)): for example φ(2)=3, φ(3)=8, φ(6)=24. and φ(5)=20, φ(11)=10, φ(55)=20

What about powers of primes? It appears that φ(pn)=pn-1φ(p) for n>1. Since φ(2)=3, this predicts φ(4)=6, φ(8)=12, φ(16)=24, φ(32)=48, φ(64)=96. And so it is.

But there are some surprises. Often φ(N)>N; but φ(19)=18, φ(21)=16 (LCM(φ(3)φ(7))), and so on.

After writing the above, I searched on "factors of fibonacci numbers" (no quotes) which led me to http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibmaths.html; this has a lot more interesting stuff about Fibonacci numbers.

Thursday, December 31, 2009

Dentistry and Math

Back in the early '70s, I used to hang out some evenings (once a week maybe?) at the UH math department, where someone would give a talk and then we would go to "Chico's" at the foot of St. Louis Heights (where City Mill is today). Most of the guys would drink beer but I'd have a 7-up or similar (I was under age).

These were interesting characters. One of them, a PhD student, said on one evening that he didn't believe the fundamental theorem of calculus. I don't know how you can be working on a Ph.D in mathematics and not believe the fundamental theorem of calculus, but there you are.

One evening, a professor (it might have been Dr. Wallen, department chair) told us about his dentist. (I've told this story 2-3 times on this vacation, and as the lovely Carol points out, I laughed out loud each time, so I decided I should write it down.) So he was at the dentist one day, and the dentist asked (you know how they do, when your mouth is full of whatever and you can't answer), "So what do you do?"

"Mf-fa-muh-fix," he replied.

The dentist made some enthusiastic noises, and the professor thought, yeah right, and endured the rest of his dental treatment. But as he was leaving, the dentist said, "Wait, when can I come over?"

Come over?

"Yeah, come over and do math. I have some papers..."

So at the appointed hour some days later, the prof opens the door to find his dentist with a sheaf of papers and a bottle of vodka. (This is the part where I always laugh. Dentistry, vodka, math -- what a great combo!) So they drink and the prof looks over the dentist's papers.

Relating this story to us, the prof said, "This guy was powerful." He had worked out a conjecture regarding the infinite series Σn 1/nx; he wasn't sure, but it seemed to him that if x was bigger than 1, then the series would converge, otherwise not.

It turned out that this was correct; if x=2, the sum converges to π2/6; if x=1, it diverges; if x=–1, it converges, but I forget what it converges to. I thought this was called "Cauchy's theorem," but a quick search (it has been about 35 years) doesn't connect that name to that theorem.

The most recent occasion for telling this story was when talking with my nephew (currently taking high school calculus) about some of my experiences "when I was your age." It was fun re-living those experiences, and also helping him review some of his math and giving him a preview of the fundamental theorem of calculus (which I actually do believe, ftr).

Oops! November 2014 update

OK, that part about –1 is completely wrong. What I meant was, the series 1/1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6… which is not Σn 1/n–1; it's actually Σn 1/(-n)1