The Fibonacci sequence is defined by the recurrence relation:
Fn=Fn−1+Fn−2, 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ϕ−1We're looking for the first one that has at least d digits, so we want:
where ϕ=1+√52
log10(Fn)≥dWe 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:
log10(ϕn−(−ϕ)−n2ϕ−1)≥d
ϕn−(−ϕ)−n2ϕ−1≈ϕn2ϕ−1 for larger nThis 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