Skip to content

Instantly share code, notes, and snippets.

@tehviking
Created August 24, 2010 04:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tehviking/546963 to your computer and use it in GitHub Desktop.
Save tehviking/546963 to your computer and use it in GitHub Desktop.
# fibonacci.rb
class Euler
def fib(n)
curr = 0
succ = 1
n.downto(0) do |x|
curr, succ = curr + succ, curr
end
return curr
end
def sum_fib(limit)
sum = 0
n = 0
fib_n = fib(n)
while fib_n < limit
sum += fib_n if fib_n % 2 == 0
n += 1
fib_n = fib(n)
end
sum
end
end
# fibonacci_test.rb
require "test/unit"
require "fibonacci"
class TestFibonacci < Test::Unit::TestCase
def test_fib
e = Euler.new
assert_equal(8, e.fib(5))
assert_equal(89, e.fib(10))
assert_equal(165580141, e.fib(40))
end
def test_sum_fib
e = Euler.new
assert_equal(10, e.sum_fib(10))
assert_equal(4613732, e.sum_fib(4000000))
end
end
@imsaar
Copy link

imsaar commented Aug 24, 2010

I reread the problem and I think your interpretation is correct. It is asking for sum of all even fib numbers less than 4 Million
http://projecteuler.net/index.php?section=problems&id=2

I think the using the fib(n) in while and twice in the subsequent line is inefficient.
Just store the fib(n) in a variable fib_n = fib(n) and use it in all places in the same iteration in the sum_fib method.

@tehviking
Copy link
Author

It looks like I have to redefine the fib_n variable first and during each loop, is that correct?

This was fun, thanks a lot!

@imsaar
Copy link

imsaar commented Aug 25, 2010

The way you have it look good.

Another way would be to be to move the assignment in the while test hence making it DRYer

while fib_n = fib(n) < limit
  sum += fib_n if fib_n % 2 == 0
  n += 1
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment