Project Euler: Problem 6 in Ruby

I thought this one was way too easy compared the the last one. There’s some mathematical trickery you can do to speed things up, but the straight-forward solution is running in .009s so I’m going to call this one “done”.

Problem #6

The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + … + 10^(2) = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)^(2) = 55^(2) = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

max = 100

def sum_of_squares max
  total = 0
  max.times do |i|
    i += 1
    total += i ** 2
  end
  total
end

def square_of_sums max
  total = 0
  max.times do |i|
    i += 1
    total += i
  end
  total ** 2
end

puts square_of_sums(max) - sum_of_squares(max)

I think kode had a neat solution in the forums:

sum, variable = 0, 0
100.downto(1) { |x| sum+=x; variable += (x*x) }
sum_square = sum*sum
puts sum_square - variable