Commit 755ab28

mo khan <mo@mokhan.ca>
2015-02-10 21:26:48
compute sum of all even fib numbers under 4,000,000.
1 parent c529b96
Changed files (1)
spec/euler/problem_two_spec.rb
@@ -0,0 +1,37 @@
+#Each new term in the Fibonacci sequence is generated by adding the previous two terms. 
+#By starting with 1 and 2, the first 10 terms will be:
+
+#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+
+#By considering the terms in the Fibonacci sequence whose values do not exceed 
+#four million, find the sum of the even-valued terms.
+describe "problem two" do
+  def fib
+    Enumerator.new do |yielder|
+      x, y = 1, 2
+      loop do
+        yielder.yield x
+        tmp = x
+        x = y
+        y = tmp + y
+      end
+    end
+  end
+
+  def sum_of_first(n)
+    fib.take(n).inject(0) do |memo, x|
+      memo + x
+    end
+  end
+
+  it "computes the sum" do
+    result = sum_of_first(10)
+    expect(result).to eql([1, 2, 3, 5, 8, 13, 21, 34, 55, 89].inject(0) {|memo, x| memo + x })
+  end
+
+  it "accumulates" do
+    items = fib.take_while { |n| n < 4_000_000 }.find_all(&:even?)
+    result = items.inject(0) { |memo, x| memo + x }
+    expect(result).to eql(4613732)
+  end
+end