002 Even Fibonacci numbers.sf 677 B

1234567891011121314151617181920212223242526272829
  1. #!/usr/bin/ruby
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # 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:
  6. # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  7. # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
  8. # https://projecteuler.net/problem=2
  9. # Runtime: 0.160s
  10. func sum_even_fibs(max) {
  11. var (a, b) = (0, 1)
  12. var sum = 0
  13. while (a <= max) {
  14. (a, b) = (b, a + b)
  15. sum += a if a.is_even
  16. }
  17. return sum
  18. }
  19. say sum_even_fibs(4e6)