095 Amicable chains.pl 638 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 09 October 2016
  5. # Website: https://github.com/trizen
  6. # https://projecteuler.net/problem=95
  7. # Runtime: 6.870s
  8. use 5.010;
  9. use strict;
  10. use integer;
  11. use ntheory qw(divisor_sum);
  12. my $limit = 1e6;
  13. my %chain;
  14. foreach my $n (1 .. $limit) {
  15. my $len = 0;
  16. my $orig = $n;
  17. my %seen;
  18. while (1) {
  19. my $sum = divisor_sum($n) - $n;
  20. last if $sum > $limit;
  21. last if $seen{$sum}++;
  22. $n = $sum;
  23. ++$len;
  24. }
  25. if (exists $seen{$orig}) {
  26. $chain{$len} //= $orig;
  27. }
  28. }
  29. say $chain{(sort { $b <=> $a } keys %chain)[0]};