alexandrian_integers.pl 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # Date: 18 August 2016
  4. # License: GPLv3
  5. # Website: https://github.com/trizen
  6. # Get the nth Alexandrian integer.
  7. # See also: https://oeis.org/A147811
  8. # https://projecteuler.net/problem=221
  9. use 5.010;
  10. use strict;
  11. use warnings;
  12. use ntheory qw(divisors);
  13. sub nth_alexandrian {
  14. my ($nth) = @_;
  15. return 120 if $nth == 3; # hmm...
  16. my %nums;
  17. my $count = 0;
  18. my $prev = 6;
  19. OUT: foreach my $n (1 .. $nth) {
  20. foreach my $d (divisors($n * $n + 1)) {
  21. my $q = $n + $d;
  22. my $r = ($n + ($n * $n + 1) / $d);
  23. last if $q > $r;
  24. my $A = $n * $q * $r;
  25. --$count if ($A < $prev);
  26. if (not exists $nums{$A}) {
  27. undef $nums{$A};
  28. $prev = $A;
  29. last OUT if (++$count == $nth);
  30. }
  31. }
  32. }
  33. +(sort { $a <=> $b } keys %nums)[$nth - 1];
  34. }
  35. foreach my $n (1 .. 20) {
  36. say "A($n) = ", nth_alexandrian($n);
  37. }
  38. __END__
  39. A(1) = 6
  40. A(2) = 42
  41. A(3) = 120
  42. A(4) = 156
  43. A(5) = 420
  44. A(6) = 630
  45. A(7) = 930
  46. A(8) = 1428
  47. A(9) = 1806
  48. A(10) = 2016
  49. A(11) = 2184
  50. A(12) = 3192
  51. A(13) = 4950
  52. A(14) = 5256
  53. A(15) = 8190
  54. A(16) = 8364
  55. A(17) = 8970
  56. A(18) = 10296
  57. A(19) = 10998
  58. A(20) = 12210