Question
The Fibonacci sequence is defined by the recurrence relation:
Hence the first 12 terms will be:
The 12th term, , is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
Clojure
#!/usr/bin/env clojure
(def fibs
(lazy-cat [(BigInteger/ZERO) (BigInteger/ONE)] (map + fibs (rest fibs))))
(println (count (take-while #(< % (.pow (BigInteger/TEN) 999)) fibs)))
Haskell
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
main :: IO ()
main = print $ head [i | i <- [1..], (==1000) . length . show $ fibs !! i]
Ruby
#!/usr/bin/env ruby
i = 1
t1, t2 = 0, 1
while t2.to_s.length < 1000
t1, t2 = t2, t1 + t2
i += 1
end
puts i
Rust
fn main() {
let mut a = vec![0];
let mut b = vec![1];
let mut n = 1;
while b.len() < 1000 {
let tmp = b.clone();
let mut carry = 0;
for i in 0..b.len() {
if i >= a.len() {
a.push(0);
}
let mut digit = a[i];
digit = b[i] + digit + carry;
carry = digit / 10;
a[i] = digit % 10;
}
if carry > 0 {
a.push(carry);
}
b = a;
a = tmp;
n += 1;
}
println!("{}", n);
}