Tuesday, January 10, 2012

Unlocking the Grid

Today I spent more time solving Project Euler problems. I cranked through a number of problems, leaving a couple of them solvable but unsolved. It takes forever to run larger calculations on my iBook G4, especially if you're writing double for-loops to do millions of calculations. Maybe this means that I should use a different machine, but I think it's more likely that I need to think of a clever way to rewrite my code to avoid duplicate calculations.

For example:

# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.

def prime_array
  numbers = (2..7).to_a
  divisor = 2
  while divisor<10
    numbers.each do |x|
      numbers.delete(x) if x%divisor == 0 && x != divisor
    end
    divisor += 1
  end
  return numbers
end

def sum_of_primes
  sum = 0
  prime_array.each do |x|
    sum += x
  end
  return sum
end
 
puts sum_of_primes

# This takes forever to calculate


I put this problem aside for awhile and kept cranking through the problem set until I hit big one: The Grid Problem.

This is a fun one. I've run into a few stumbling blocks, but I'm hoping to finish it tomorrow.

No comments:

Post a Comment