Skip to content

Instantly share code, notes, and snippets.

@michaeltwofish
Created February 16, 2011 03:25
Show Gist options
  • Save michaeltwofish/828802 to your computer and use it in GitHub Desktop.
Save michaeltwofish/828802 to your computer and use it in GitHub Desktop.
Euler problem 2
N = 4000000
# Brute force
def fib(num)
if num < 2
num
else
fib(num - 2) + fib(num - 1)
end
end
n = 0
fib_n = 0
sum = 0
while fib_n < N do
fib_n = fib(n)
sum = sum + fib_n if (n % 3 == 0)
n = n + 1
end
puts "Brute force: #{sum}"
# Smarter
fib_n = 2
sum = 0
ratio = 1.61803399
even_ratio = ratio**3
while fib_n < N do
sum = sum + fib_n
fib_n = (fib_n * even_ratio).round
end
puts "Smarter: #{sum}"
@heptat
Copy link

heptat commented Feb 16, 2011

Strange looking C o_O

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