Multiply two large numbers in Java [closed]

人走茶凉 提交于 2019-12-02 15:05:02

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!