project-euler/src/Julia/Problem051.jl

70 lines
2.0 KiB
Julia

#=
Created on 25 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for Problem 51 of Project Euler
https://projecteuler.net/problem=51
=#
using BenchmarkTools
using Primes
function Problem51()
#=
By replacing the 1st digit of the 2-digit number *3, it turns out that
six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit
number is the first example having seven primes among the ten generated numbers,
yielding the family:
56003, 56113, 56333, 56443, 56663, 56773, and 56993.
Consequently 56003, being the first member of this family, is the smallest prime
with this property.
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.
=#
primes_list = primes(57_000,1_000_000)
digits = Dict('0'=>[], '1'=>[], '2'=>[],'3'=>[], '4'=>[], '5'=>[], '6'=>[], '7'=>[], '8'=>[], '9'=>[])
for d in keys(digits)
for p in primes_list
p_ = string(p)
dummy = string(d)
if length(collect(eachmatch(Regex(dummy), p_))) == 3 && p_[end] != string(d)
push!(digits[d],p)
end
end
end
for d in ['0', '1', '2']
for p in digits[d]
res = 0
i = 10
dummy = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for D in deleteat!(dummy, findall(x->x==d, dummy))
i -= 1
q = parse(Int, replace(string(p), d=>D))
if isprime(q) && q > 57_000
res += 1
end
if i + res < 7
break
end
end
if res == 7
return p
end
end
end
end
println("Time to evaluate Problem $(lpad(51, 3, "0")):")
@btime Problem51()
println("")
println("Result for Problem $(lpad(51, 3, "0")): ", Problem51())