secant_numbers.pl 901 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/perl
  2. # Algorithm for computing the secant numbers (also known as Euler numbers):
  3. #
  4. # 1, 1, 5, 61, 1385, 50521, 2702765, 199360981, 19391512145, 2404879675441, 370371188237525, ...
  5. #
  6. # Algorithm presented in the book:
  7. #
  8. # Modern Computer Arithmetic
  9. # - by Richard P. Brent and Paul Zimmermann
  10. #
  11. # See also:
  12. # https://oeis.org/A000364
  13. # https://en.wikipedia.org/wiki/Euler_number
  14. use 5.010;
  15. use strict;
  16. use warnings;
  17. use Math::GMPz;
  18. sub secant_numbers {
  19. my ($n) = @_;
  20. my @S = (Math::GMPz::Rmpz_init_set_ui(1));
  21. foreach my $k (1 .. $n) {
  22. Math::GMPz::Rmpz_mul_ui($S[$k] = Math::GMPz::Rmpz_init(), $S[$k - 1], $k);
  23. }
  24. foreach my $k (1 .. $n) {
  25. foreach my $j ($k + 1 .. $n) {
  26. Math::GMPz::Rmpz_addmul_ui($S[$j], $S[$j - 1], ($j - $k + 2) * ($j - $k));
  27. }
  28. }
  29. return @S;
  30. }
  31. say join(', ', secant_numbers(10));