Fun and Easy Fibonacci Trick

So, Futility Closet has a lovely trick for generating the first 100-some Fibonacci numbers. It’s not efficient or anything, but it is pretty fun.

The trick is that the decimal expansion of 1 / 999,999,999,999,999,999,999,998,999,999,999,999,999,999,999,999 generates a Fibonacci number every 24 digits. That’s an easy number to create in Perl 6:

> my $n = 1.FatRat / 999_999_999_999_999_999_999_998_999_999_999_999_999_999_999_999
0.0000000000000000000000000000000000000000000000010

The default decimal expansion doesn’t have enough digits to see this effect. But luckily, it’s easier to get a better expansion:

> $n.base(10,2400).comb(/\d ** 24/).join("\n")
000000000000000000000000
000000000000000000000001
000000000000000000000001
000000000000000000000002
000000000000000000000003
000000000000000000000005
000000000000000000000008
000000000000000000000013
...
000083621143489848422977
000135301852344706746049
000218922995834555169026

We can check that it works by comparing it to a more normal p6 way of calculating the Fibonacci series:

> [&&] $n.base(10,2400).comb(/\d ** 24/).map(+*) Z== (0, 1, *+* ... *)
True
Advertisements

One Response to “Fun and Easy Fibonacci Trick”

  1. 2015.27 It was HOT | Weekly changes in and around Perl 6 Says:

    […] Foster blogged about a Fun and Easy Fibonacci Trick. FatRats for The […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: