Sat, 20 Mar 2004

Fibonacci numbers

I’ve been reading GEB. Hofstadter loves Fibonacci numbers.

This morning I got up early and read a section in GEB while the house was quiet and the sun was coming up. To test understanding, Hofstadter listed several items, some well formed, some not. As an answer key, he wrote, “Those whose numbers are Fibonacci numbers are not well formed.”

On a sheet of paper I wrote the Fibonacci sequence far enough to check the answers. Then, just to exercise tired brain cells, I started adding as fast as I could to extend the sequence.

I had about 80 numbers written when I grew weary of the exercise. But staring at the page of digits, I couldn’t rest without knowing if and where I had made any errors.

So, I headed down to the computer and wrote a couple of perl one-liners.

I love Perl, and I especially enjoy writing little one-liners I can execute from the command line without having to create a source file. My first attempt looked like this:

perl -e '@f=(1,1);print$f[@f]=$f[-1]+$f[-2],"\n"while@f<80'

That resulted in the last few terms printing in scientific notation, e.g., 2.34167283484677e+16. I wanted the full integer representation. The final version prints the term number and the full integer representation using the the Math::BigInt module. It also takes the number of terms as an argument and the command line shown pipes the output to less for easy viewing.

perl -MMath::BigInt -e '$one=Math::BigInt->new(1);
@f=($one,$one); print@f+1,": ",$f[@f]=$f[-1]+$f[-2],
"\n"while@f<$ARGV[0]' 80|less

[/programming] [link]

About this weblog

This site is the personal weblog of Marc Mims. You can contact Marc by sending e-mail to:
[email protected].

Marc writes here about cycling, programming, Linux, and other items of personal interest.

This site is syndicated with RSS.

Archives

Credits

CSS stolen from Tom Coates who didn't even complain.