Aug
17
In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 47.
This solution shows off the power of built-in Ruby Array methods. You will notice Array.uniq returns a new array by removing duplicate values in self and Array.transpose, which I haven’t used prior to this solution, assumes that self is an array of arrays and transposes the rows and columns. I think the code below is a perfect example of how this method should/could be used.
As always, any feedback is welcome.
# Euler 47
# http://projecteuler.net/index.php?section=problems&id=47
# The first two consecutive numbers to have two distinct
# prime factors are:
#
# 14 = 2 x 7
# 15 = 3 x 5
#
# The first three consecutive numbers to have three
# distinct prime factors are:
#
# 644 = 2² x 7 x 23
# 645 = 3 x 5 x 43
# 646 = 2 x 17 x 19.
#
# Find the first four consecutive integers to have four
# distinct primes factors. What is the first of these numbers?
timer_start = Time.now
require 'mathn'
distinct_factors, consecutive_integers = 4, 4
counter, answer, i = 0, 0, 1
while counter < consecutive_integers
primes, powers = i.prime_division.transpose
if (primes != nil && primes.uniq.length >= distinct_factors)
counter += 1
answer = i if counter == 1
else
counter, answer = 0, 0
end
i += 1
end
puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"