rational_continued_fractions.pl 891 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 31 July 2016
  5. # Website: https://github.com/trizen
  6. # Recursive evaluation of continued fractions rationally,
  7. # by computing the numerator and the denominator individually.
  8. # For every continued fraction, we have the following relation:
  9. #
  10. # n
  11. # | / a(k) kn(n)
  12. # |/ ----- = -------
  13. # | \ b(k) kd(n)
  14. # k=0
  15. use 5.010;
  16. use strict;
  17. use warnings;
  18. use Memoize qw(memoize);
  19. no warnings qw(recursion);
  20. use experimental qw(signatures);
  21. memoize('kn');
  22. memoize('kd');
  23. sub a($n) {
  24. $n**2;
  25. }
  26. sub b($n) {
  27. 2 * $n + 1;
  28. }
  29. sub kn($n) {
  30. $n < 2
  31. ? ($n == 0 ? 1 : 0)
  32. : b($n - 1) * kn($n - 1) + a($n - 1) * kn($n - 2);
  33. }
  34. sub kd($n) {
  35. $n < 2
  36. ? $n
  37. : b($n - 1) * kd($n - 1) + a($n - 1) * kd($n - 2);
  38. }
  39. for my $i (0 .. 10) {
  40. printf("%2d. %20d %20d\n", $i, kn($i), kd($i));
  41. }