bell_numbers_mpz.pl 893 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/perl
  2. # Fast algorithm for computing the first `n` Bell numbers, using Aitken's array (optimized for space).
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Bell_number
  5. use 5.020;
  6. use strict;
  7. use warnings;
  8. use Math::GMPz;
  9. use experimental qw(signatures);
  10. sub bell_numbers($n) {
  11. my @acc;
  12. my $t = Math::GMPz::Rmpz_init();
  13. my @bell = (Math::GMPz::Rmpz_init_set_ui(1));
  14. foreach my $k (1 .. $n) {
  15. Math::GMPz::Rmpz_set($t, $bell[-1]);
  16. foreach my $item (@acc) {
  17. Math::GMPz::Rmpz_add($t, $t, $item);
  18. Math::GMPz::Rmpz_set($item, $t);
  19. }
  20. unshift @acc, Math::GMPz::Rmpz_init_set($bell[-1]);
  21. push @bell, Math::GMPz::Rmpz_init_set($acc[-1]);
  22. }
  23. @bell;
  24. }
  25. say join ', ', bell_numbers(15);
  26. __END__
  27. 1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975, 678570, 4213597, 27644437, 190899322, 1382958545