Buddhi Weerasinghe Buddhi Weerasinghe - 1 month ago 7
Java Question

Multiply two large numbers in Java

public long Fib(int a1, int a2, int i){
if(i==1){
return a1;
}else if(i==2){
return a2;
}else{
long l1 = Fib(a1, a2, i-1);
long l2 = Fib(a1, a2, i-2);

long val = l2 + (l1*l1);
return val;
}
}


I wrote this code to find a Modified Fibonacci of function of t(i+2) = t(i) + t(i+1)^2 where t(i) is the answer when we find ith iterartion.
But when I find t(10), it gives a separate answer.
But I got correct answers till t(9). I tried BigInteger method but it gives errors.

Answer

You should modify your code a little if you want to use BigIntegers. Something like:

public class ModifiedFib
{
    static BigInteger Fib(int a1, int a2, int i)
    {
        if (i <= 0)
            return BigInteger.ZERO;
        else if (i == 1)
            return BigInteger.valueOf(a1);
        else if (i == 2)
            return BigInteger.valueOf(a2);
        else
        {
            BigInteger b1 = Fib(a1, a2, i - 1);
            BigInteger b2 = Fib(a1, a2, i - 2);

            return b1.multiply(b1).add(b2);
        }
    }

    public static void main(String[] args)
    {
        for (int i = -1; i <= 11; i++)
            System.out.println("i = " + i + ": " + Fib(0, 1, i));
    }
}

I added a check for i <= 0 and return ZERO in that case. I don't know what inputs you have, but in main(), I have a simple loop demo-ing the function.

Output:

i = -1: 0
i = 0: 0
i = 1: 0
i = 2: 1
i = 3: 1
i = 4: 2
i = 5: 5
i = 6: 27
i = 7: 734
i = 8: 538783
i = 9: 290287121823
i = 10: 84266613096281243382112
i = 11: 7100862082718357559748563880517486086728702367
Comments