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
July 6, 2015 at 7:44 pm |
[…] Foster blogged about a Fun and Easy Fibonacci Trick. FatRats for The […]