Posts Tagged ‘project euler’

Project Euler Problem 40

Thursday, October 29th, 2009

Project Euler Problem 40

In my opinion, this was the easiest problem so far. The brute-force method is easy to implement and runs very fast.

This is the code:

$fraction = ''
 
1.upto(1000000) do |i|
  $fraction << i.to_s
end
 
def d_(n)
  $fraction[n-1].to_i
end
 
puts d_(1) * d_(10) * d_(100) * d_(1000) * d_(10000) * d_(100000) * d_(1000000)

It runs in slightly lesser than one second.

The last line isn’t very Ruby-ish because I copied it from the problem description page, because I’m too lazy to write it myself. That’s also why I have a d_(n) function.

Project Euler Problem 21 (Ruby)

Thursday, September 24th, 2009

If you intend to solve the problem on your own, I wouldn’t recommend reading any further.

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a \neq b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

(Problem 21 – Project Euler)

def d(n)
  total = 0
  1.upto n/2 do |i|
    if (n % i) == 0
      total += i
    end  
  end
  total
end
 
amicable_sum = 0
 
10000.times do |a|
  b = d(a)
  if d(b) == a && b > a
    amicable_sum += a + b
  end
end
 
puts amicable_sum

My version of d(n) isn’t as efficient as the one in the PDF you get after solving the problem, but it gets the job done.

Running it takes around 8.5 seconds on my machine. That’s not too bad for ~20 lines of code.

Project Euler #48 in Ruby

Thursday, April 2nd, 2009

Note: Don’t look at the code if you intend to solve the problem later.

Problem 48 – Project Euler

I was surprised at how easy this turned out to be. It is really, really simple because with Ruby, the only limit on how big an integer can get is how much memory you have available. Here’s my solution:

# Project Euler, 48
start = Time.now
 
n = 1
sum = 0
 
1000.times do
  sum += n**n
  n += 1
end
 
puts sum.to_s[-10..-1]
puts "Time taken: #{Time.now-start}"

It takes a fifth of a second on my laptop running Ruby 1.9.1.