number_of_connected_permutations.pl 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 03 December 2017
  4. # https://github.com/trizen
  5. # A new algorithm for computing number of connected permutations of [1..n].
  6. # See also:
  7. # https://oeis.org/A003319
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. use Math::AnyNum qw(:overload factorial binomial);
  12. sub number_of_connected_permutations {
  13. my ($n) = @_;
  14. my @P = (1);
  15. foreach my $i (1 .. $n) {
  16. foreach my $k (0 .. $i - 1) {
  17. $P[$i] += $P[$k] / binomial($i, $k+1);
  18. }
  19. }
  20. map { $P[$_] * factorial($_) } 0 .. $#P;
  21. }
  22. my @P = number_of_connected_permutations(20);
  23. foreach my $i (0 .. $#P) {
  24. say "P($i) = $P[$i]";
  25. }
  26. __END__
  27. P(0) = 1
  28. P(1) = 1
  29. P(2) = 3
  30. P(3) = 13
  31. P(4) = 71
  32. P(5) = 461
  33. P(6) = 3447
  34. P(7) = 29093
  35. P(8) = 273343
  36. P(9) = 2829325
  37. P(10) = 31998903
  38. P(11) = 392743957
  39. P(12) = 5201061455
  40. P(13) = 73943424413
  41. P(14) = 1123596277863
  42. P(15) = 18176728317413
  43. P(16) = 311951144828863
  44. P(17) = 5661698774848621
  45. P(18) = 108355864447215063
  46. P(19) = 2181096921557783605
  47. P(20) = 46066653228356851631