Created
May 6, 2009 12:29
-
-
Save itsthomson/107503 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
#---------------- | |
# euler2.rb | |
# Thomson Nguyen | |
#---------------- | |
# I try to learn ruby by solving Project Euler | |
# puzzles. (http://projecteuler.net) | |
# | |
# Feel free to take a look at my progress and | |
# comment, but don't laugh! | |
# | |
# All code subject to MIT License, blah blah | |
# | |
# | |
# 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, ... | |
# | |
# Find the sum of all the even-valued terms in | |
# the sequence which do not exceed four million. | |
# | |
# So at first I tried a recursive iterative approach: | |
def fib(n) | |
return n if (0..1).include? n | |
fib(n-1) + fib(n-2) if n > 1 | |
end | |
def fibsum(k) | |
i=0 | |
running=0 | |
while i <= k | |
running = running + fib(i) | |
i += 1 | |
end | |
return running-1 # Adhering to problem convention | |
end | |
# But stopped after realizing it would take forever | |
# to calculate large sums! | |
# A better way to appraoch this is to use an array to | |
# keep all of our fib numbers in one place: | |
def fibarr(n) | |
return n if (0..1).include? n | |
array = [0, 1] | |
n.times do | |
array.push(array[-1] + array[-2]) | |
end | |
return array[2...n] | |
end | |
# Now we have a linear-time computation of fib numbers | |
# in an array. inject is a great rubyism that we can | |
# use to sum up the entries in this array: | |
class Array | |
def sum | |
inject() { |sum,element| sum+element } | |
end | |
end | |
# Now we can filter for even numbers and check the | |
# 4 million condition...but at this point, I remembered | |
# every third number in the fib sequence is even. | |
# | |
sum=0;a=1;b=1;c=a+b | |
while c < 4000000 | |
sum=sum+c | |
a=b+c | |
b=c+a | |
c=a+b | |
end | |
puts sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment