Created
August 24, 2010 04:37
-
-
Save tehviking/546963 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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!
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
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.