051 Prime digit replacements -- v2.pl 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 18 March 2023
  4. # 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: 2.179s
  8. use 5.036;
  9. use ntheory qw(:all);
  10. use List::Util qw(uniq);
  11. foreach my $n (1 .. 15) {
  12. my %table;
  13. foreach my $p (@{primes(10**($n - 1), 10**$n - 1)}) {
  14. my @s = split(//, $p);
  15. my %indices;
  16. foreach my $i (0 .. $#s) {
  17. push @{$indices{$s[$i]}}, $i;
  18. }
  19. foreach my $idx (values %indices) {
  20. foreach my $i (1 .. scalar(@$idx)) {
  21. forcomb {
  22. my $key = $p;
  23. foreach my $i (@{$idx}[@_]) {
  24. substr($key, $i, 1, '*');
  25. }
  26. push @{$table{$key}}, $p;
  27. } scalar(@$idx), $i;
  28. }
  29. }
  30. }
  31. my $min = +'inf';
  32. foreach my $value (values %table) {
  33. if (scalar(@$value) == 8 and $value->[0] < $min) {
  34. say "Found prime group: [@{$value}]";
  35. $min = $value->[0];
  36. }
  37. }
  38. if ($min != +'inf') {
  39. say $min;
  40. last;
  41. }
  42. }