Loading [MathJax]/jax/output/CommonHTML/jax.js

Problem 025: 1000-digit Fibonacci Number

From Project Euler:

The Fibonacci sequence is defined by the recurrence relation:

Fn=Fn1+Fn2, where F1=1 and F2=1.
Hence the first 12 terms will be:

F1=1
F2=1
F3=2
F4=3
F5=5
F6=8
F7=13
F8=21
F9=34
F10=55
F11=89
F12=144

The 12th term, F12, is the first term to contain three digits.

What is the index of the first term in the Fibonacci sequence to contain 1000 digits?

This problem can be solved analytically, and so runs in constant time. It all starts with Binet's formula, which states that the nth Fibonacci number Fn has the expression:
Fn=ϕn(ϕ)n2ϕ1
where ϕ=1+52
We're looking for the first one that has at least d digits, so we want:
log10(Fn)d
log10(ϕn(ϕ)n2ϕ1)d
We want to get a closed-form expression for n in terms of d, which is a challenge with this formula (if possible at all). Instead though if we realize that (ϕ)n diminishes very quickly, we can do an optimization:
ϕn(ϕ)n2ϕ1ϕn2ϕ1 for larger n
This can give us a closed-form expression for n in terms of d:
n=d+log(2ϕ1)log(ϕ)
Translating from math to Clojure:
(defn min-digits-fibonacci
  "Gets the first Fibonacci number with the specified number of digits."
  [num-digits]
  (let [phi (/ (+ 1.0 (Math/sqrt 5.0)) 2.0)]
    (int (Math/ceil (/ (+ (- num-digits 1)
                          (Math/log10 (- (* 2.0 phi) 1.0)))
                       (Math/log10 phi))))))

As expected, this runs very quickly:
$ lein run
Processing...
Index is: 4782
"Elapsed time: 2.180435 msecs"

No comments:

Post a Comment