051 Prime digit replacements.pl 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.
  6. # https://projecteuler.net/problem=51
  7. # Runtime: 3.393s
  8. use 5.014;
  9. use ntheory qw(primes forcomb);
  10. foreach my $n (1 .. 15) {
  11. my %table;
  12. foreach my $p (@{primes(10**($n - 1), 10**$n - 1)}) {
  13. my @s = split(//, $p);
  14. foreach my $i (1 .. $n - 1) {
  15. forcomb {
  16. if (length(join('', @s[@_]) =~ tr/0-9//sr) == 1) {
  17. my %ind;
  18. @ind{@_} = ();
  19. push @{$table{join('', map { exists($ind{$_}) ? '*' : $s[$_] } 0 .. $#s)}}, $p;
  20. }
  21. } length($p)-1, $i;
  22. }
  23. }
  24. my $min = +'inf';
  25. foreach my $value (values %table) {
  26. if ($#{$value} == 7 and $value->[0] < $min) {
  27. say "Found prime group: [@{$value}]";
  28. $min = $value->[0];
  29. }
  30. }
  31. if ($min != +'inf') {
  32. say $min;
  33. last;
  34. }
  35. }