Aug
11
In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 35.
For this solution, I played with pushing and popping on and off of a stack, err, Ruby array. And rotating the digits is brought to you by our good friend, shift. Execution time is slow (35 seconds) but it didn’t take me long to code so, once again, I’m happy with the result.
As always, any feedback is welcome.
# Euler 35
# http://projecteuler.net/index.php?section=problems&id=35
# The number, 197, is called a circular prime because all
# rotations of the digits: 197, 971, and 719, are
# themselves prime.
#
# There are thirteen such primes below 100:
# 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#
# How many circular primes are there below one million?
timer_start = Time.now
require 'mathn'
def circular_prime?(i)
nums = i.to_s.chars.to_a
nums.length.times do
return false if (!nums.join().to_i.prime?)
# "pop" digit off the front and rotate to the end
nums.push nums[0]
nums.shift
end
return true
end
answer = 0
Prime.each { |x|
break if x >= 1_000_000
answer += 1 if circular_prime?(x)
}
puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"