Skip to content

Instantly share code, notes, and snippets.

@paulghaddad
Created December 17, 2014 17:48
Show Gist options
  • Save paulghaddad/ea8afc892aee97fe60cf to your computer and use it in GitHub Desktop.
Save paulghaddad/ea8afc892aee97fe60cf to your computer and use it in GitHub Desktop.
difference_of_squares.rb

Difference Of Squares

Find the difference between the sum of the squares and the square of the sums of the first N natural numbers.

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.

Source

Problem 6 at Project Euler view source

require 'minitest/autorun'
require_relative 'squares'
class SquaresTest < MiniTest::Unit::TestCase
def test_square_of_sums_to_5
assert_equal 225, Squares.new(5).square_of_sums
end
def test_sum_of_squares_to_5
assert_equal 55, Squares.new(5).sum_of_squares
end
def test_difference_of_sums_to_5
assert_equal 170, Squares.new(5).difference
end
def test_square_of_sums_to_10
assert_equal 3025, Squares.new(10).square_of_sums
end
def test_sum_of_squares_to_10
assert_equal 385, Squares.new(10).sum_of_squares
end
def test_difference_of_sums_to_10
assert_equal 2640, Squares.new(10).difference
end
def test_square_of_sums_to_100
assert_equal 25502500, Squares.new(100).square_of_sums
end
def test_sum_of_squares_to_100
assert_equal 338350, Squares.new(100).sum_of_squares
end
def test_difference_of_sums_to_100
assert_equal 25164150, Squares.new(100).difference
end
end
class Squares
attr_reader :numbers
def initialize(high_number)
@numbers = (1..high_number)
end
def square_of_sums
sums = numbers.inject(:+)
sums ** 2
end
def sum_of_squares
numbers.inject { |sum, n| sum + n ** 2 }
end
def difference
square_of_sums - sum_of_squares
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment