Project Euler 51: Ruby
- by Ben Griswold
In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 51.
I know I started back up with Python this week, but I have three more Ruby solutions in the hopper and I wanted to share. For the record, Project Euler 51 was the second hardest Euler problem for me thus far. Yeah.
As always, any feedback is welcome.
# Euler 51
# http://projecteuler.net/index.php?section=problems&id=51
# By replacing the 1st digit of *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.
timer_start = Time.now
require 'mathn'
def eight_prime_family(prime)
0.upto(9) do |repeating_number|
# Assume mask of 3 or more repeating numbers
if prime.count(repeating_number.to_s) >= 3
ctr = 1
(repeating_number + 1).upto(9) do |replacement_number|
family_candidate = prime.gsub(repeating_number.to_s,
replacement_number.to_s)
ctr += 1 if (family_candidate.to_i).prime?
end
return true if ctr >= 8
end
end
false
end
# Wanted to loop through primes using Prime.each
# but it took too long to get to the starting value.
n = 9999
while n += 2
next if !n.prime?
break if eight_prime_family(n.to_s)
end
puts n
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"