summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2015-02-23 18:22:42 -0700
committermo khan <mo@mokhan.ca>2015-02-23 18:22:42 -0700
commit531e57be4101899c8d9b80d13795516fda31e74e (patch)
tree2e291492dd6cac77b67d2fcf1ce76f0f415d44e7
parent454a82972b73677294a575398d36a00e1137f5bf (diff)
it computes the sum of the squares and square of sums.
-rw-r--r--spec/euler/problem_six_spec.rb56
1 files changed, 56 insertions, 0 deletions
diff --git a/spec/euler/problem_six_spec.rb b/spec/euler/problem_six_spec.rb
new file mode 100644
index 0000000..d51e1f6
--- /dev/null
+++ b/spec/euler/problem_six_spec.rb
@@ -0,0 +1,56 @@
+require "spec_helper"
+
+describe "problem six" do
+ #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
+
+ class NaturalNumbers
+ include Enumerable
+ attr_reader :limit
+
+ def initialize(limit)
+ @limit = limit
+ end
+
+ def each
+ 0.upto(limit) do |n|
+ yield n
+ end
+ end
+
+ def sum_of_squares
+ sum { |n| n*n }
+ end
+
+ def square_of_the_sum
+ result = sum
+ result * result
+ end
+
+ def difference
+ square_of_the_sum - sum_of_squares
+ end
+
+ private
+
+ def sum
+ inject(0) do |memo, n|
+ memo += block_given? ? yield(n) : n
+ end
+ end
+ end
+
+ it "returns the sum of first 10 natural numbers" do
+ subject = NaturalNumbers.new(10)
+ expect(subject.sum_of_squares()).to eql(385)
+ end
+
+ it "returns the square of the sum of the first 10 natural numbers" do
+ subject = NaturalNumbers.new(10)
+ expect(subject.square_of_the_sum()).to eql(3025)
+ end
+
+ it "returns the different between the sum of the squares and the square of the sum" do
+ subject = NaturalNumbers.new(10)
+ expect(subject.difference).to eql(2640)
+ end
+end