1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- #!/usr/bin/ruby
- # Author: Daniel "Trizen" Șuteu
- # License: GPLv3
- # Website: https://github.com/trizen
- # https://projecteuler.net/problem=140
- # Runtime: 0.149s
- # After some analysis, I ended up with the following formula:
- #
- # f(x) = -(x(3x + 1)) / (x^2 + x - 1)
- #
- # which generates golden nuggets when it's called by the following rules:
- #
- # when i is even: f(fib(i) / fib(i+1))
- # when i is odd: f((fib(i+1)+lucas(i)) / (fib(i+2)+lucas(i+1)))
- func lucas(n) is cached {
- n.is_one ? 1
- : (n.is_zero ? 2
- : (lucas(n-1) + lucas(n-2)))
- }
- func fib(n) is cached {
- n.is_one ? 1
- : (n.is_zero ? 0
- : (fib(n-1) + fib(n-2)))
- }
- func f(x) {
- - x*(3*x + 1) / (x**2 + x - 1) -> round
- }
- var sum = 0
- for i in (1..30) {
- if (i.is_even) {
- sum += f(fib(i)/fib(i+1))
- }
- else {
- var a = fib(i+1)+lucas(i)
- var b = fib(i+2)+lucas(i+1)
- sum += f(a/b)
- }
- }
- say sum
|