111 Primes with runs.pl 907 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 09 February 2017
  5. # Website: https://github.com/trizen
  6. # https://projecteuler.net/problem=111
  7. # Runtime: 31.57 min
  8. # For a faster approach, see version 2.
  9. use 5.010;
  10. use strict;
  11. use warnings;
  12. use ntheory qw(forprimes vecsum todigits);
  13. my @max;
  14. my @sums;
  15. my $p;
  16. my @table;
  17. forprimes {
  18. $p = $_;
  19. $#table = -1;
  20. ++$table[$_] for todigits($p);
  21. foreach my $i (0..$#table) {
  22. my $count = $table[$i] // next;
  23. if (defined $max[$i]) {
  24. if ($count > $max[$i]) {
  25. $max[$i] = $count;
  26. $sums[$i] = $p;
  27. }
  28. elsif ($count == $max[$i]) {
  29. $sums[$i] += $p;
  30. }
  31. }
  32. else {
  33. $max[$i] = $count;
  34. $sums[$i] = $p;
  35. }
  36. }
  37. } 1000000000, 9999999999;
  38. say vecsum(grep { defined($_) } @sums);