fibonacci_closed_form.pl 472 B

12345678910111213141516171819202122232425262728
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 29 October 2015
  5. # Website: https://github.com/trizen
  6. # A simple closed-form to the Fibonacci sequence
  7. use 5.010;
  8. use strict;
  9. use warnings;
  10. sub fib {
  11. my ($n) = @_;
  12. state $S = sqrt(5);
  13. state $T = ((1 + $S) / 2);
  14. state $U = (2 / (1 + $S));
  15. state $PI = atan2(0, -'inf');
  16. ($T**$n - ($U**$n * cos($PI * $n))) / $S;
  17. }
  18. for my $n (1 .. 20) {
  19. say "F($n) = ", fib($n);
  20. }