140 Modified Fibonacci golden nuggets.sf 982 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/ruby
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # https://projecteuler.net/problem=140
  6. # Runtime: 0.149s
  7. # After some analysis, I ended up with the following formula:
  8. #
  9. # f(x) = -(x(3x + 1)) / (x^2 + x - 1)
  10. #
  11. # which generates golden nuggets when it's called by the following rules:
  12. #
  13. # when i is even: f(fib(i) / fib(i+1))
  14. # when i is odd: f((fib(i+1)+lucas(i)) / (fib(i+2)+lucas(i+1)))
  15. func lucas(n) is cached {
  16. n.is_one ? 1
  17. : (n.is_zero ? 2
  18. : (lucas(n-1) + lucas(n-2)))
  19. }
  20. func fib(n) is cached {
  21. n.is_one ? 1
  22. : (n.is_zero ? 0
  23. : (fib(n-1) + fib(n-2)))
  24. }
  25. func f(x) {
  26. - x*(3*x + 1) / (x**2 + x - 1) -> round
  27. }
  28. var sum = 0
  29. for i in (1..30) {
  30. if (i.is_even) {
  31. sum += f(fib(i)/fib(i+1))
  32. }
  33. else {
  34. var a = fib(i+1)+lucas(i)
  35. var b = fib(i+2)+lucas(i+1)
  36. sum += f(a/b)
  37. }
  38. }
  39. say sum