Java Programmer Java Programmer - 27 days ago 14
Java Question

Number of digits in the n’th Fibonacci Number

Number of digits in the n’th Fibonacci Number.

Given a number n, find the number of digits in the n’th Fibonacci Number.

Example: n = 1000, then Fibonacci number is "43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875"
and number of digit is 209

Code should be optimize enough to calculate 1000th number in Fibonacci series.

public int getLength(int n) {
//TODO: write code here.
}

Answer

You can combine Dynamic programming with biginteger class. There are other solution also available.

public int getLength(int n) {
    return String.valueOf(fabWithImprovedDP(n)).length();
}

public BigInteger fabWithImprovedDP(int n) {
    BigInteger a = BigInteger.ZERO;
    BigInteger b = BigInteger.ONE;
    BigInteger sum = BigInteger.ZERO;
    for (int i = 1; i < n; ++i) {
        sum = a.add(b);
        a = b;
        b = sum;
    }
    return sum;
}
Comments