051 Prime digit replacements.sf 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/ruby
  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: 33.514s
  8. for n in (1..Inf) {
  9. say "Sieving #{n}-digit primes..."
  10. var table = Hash()
  11. each_prime(10**(n-1), 10**n - 1, {|p|
  12. var s = p.to_s
  13. var indices = Hash()
  14. s.chars.each_kv {|k,v|
  15. indices{v} := [] << k
  16. }
  17. indices.each_value {|idx|
  18. for i in (1..idx.len) {
  19. idx.combinations(i, {|*a|
  20. table{a.reduce({|a,b| a.insert('*', b, 1) }, s)} := [] << p
  21. })
  22. }
  23. }
  24. })
  25. var min = Inf
  26. table.each_value {|value|
  27. if ((value.len == 8) && (value.head < min)) {
  28. say "Found prime group: #{value}"
  29. min = value.head
  30. }
  31. }
  32. if (min < Inf) {
  33. say "Least such prime is: #{min}"
  34. break
  35. }
  36. }