main
1require "spec_helper"
2
3describe "problem six" do
4 #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
5
6 class NaturalNumbers
7 include Enumerable
8 attr_reader :limit
9
10 def initialize(limit)
11 @limit = limit
12 end
13
14 def each
15 0.upto(limit) do |n|
16 yield n
17 end
18 end
19
20 def sum_of_squares
21 sum { |n| n*n }
22 end
23
24 def square_of_the_sum
25 result = sum
26 result * result
27 end
28
29 def difference
30 square_of_the_sum - sum_of_squares
31 end
32
33 private
34
35 def sum
36 inject(0) do |memo, n|
37 memo += block_given? ? yield(n) : n
38 end
39 end
40 end
41
42 it "returns the sum of first 10 natural numbers" do
43 subject = NaturalNumbers.new(10)
44 expect(subject.sum_of_squares()).to eql(385)
45 end
46
47 it "returns the square of the sum of the first 10 natural numbers" do
48 subject = NaturalNumbers.new(10)
49 expect(subject.square_of_the_sum()).to eql(3025)
50 end
51
52 it "returns the different between the sum of the squares and the square of the sum" do
53 subject = NaturalNumbers.new(10)
54 expect(subject.difference).to eql(2640)
55 end
56
57 it "solves the problem" do
58 subject = NaturalNumbers.new(100)
59 expect(subject.difference).to eql(25164150)
60 end
61end