Multiply two large numbers in Java [closed]

*爱你&永不变心* 提交于 2019-12-03 01:21:56

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/40253935/multiply-two-large-numbers-in-java

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