25.Fibonacci sequence to contain 1000 digits

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 first term in the Fibonacci sequence to contain 1000 digits?

import java.math.BigInteger;
public class Problem25 {

    public void Fibonacci () {
        final String bignumber = BigInteger.valueOf(10).pow(999).toString(10);
        System.out.println(bignumber  + " - "+ bignumber.length());
        BigInteger a = BigInteger.ONE;
        BigInteger b = BigInteger.ONE;
        BigInteger c = a.add(b);
        int count = 3;
        String chekc = c.toString(10);
        while (true) {
            a =b.add(c);
            chekc = a.toString(10);
            count++;
            if (chekc.length() >= bignumber.length()) break;

            b =c.add(a);
            chekc = b.toString(10);
            count++;
            if (chekc.length() >= bignumber.length()) break;

            c =a.add(b);
            count++;
            chekc = c.toString(10);
            if (chekc.length() >= bignumber.length()) break;
        }
        System.out.println(count);
    }
    public static void main(String[] args) {
        Problem25 p = new Problem25();
        p.Fibonacci ();
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: