## Hackerrank – Problem description

The problem description – Hackerrank.

## Solution

We will calculate Fibonacci numbers sequence using known algorithm. If the next number is even, add it to the result sum. We end up calculations when the next Fibonacci number is greater than upper number constraint.

I created solution in:

All solutions are also available on my GitHub profile.

## Ruby

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
def fibonacci(n) fi = (1 + Math.sqrt(5)) / 2 psi = 1 - fi return ((fi**n - psi**n) / Math.sqrt(5)).to_i end def sum_of_even_fibonacci(number) index = 3 # at index % 3 == 0 there are always even fibonacci numbers result = 0 num = fibonacci(index) while num <= number result += num index += 3 num = fibonacci(index) end return result end def sum_of_even_fibonacci_naive(number) result = 0 a = 0 b = 1 while b < number temp = a + b a = b b = temp result += a if a % 2 == 0 end return result end gets.chomp.to_i.times do input = gets.chomp.to_i puts sum_of_even_fibonacci_naive(input) end |