How to return int if BigInteger is too big for int?

Viewed 162

i'm currently trying to solve a HackerRank problem, the problem in question is called Fibonacci Modified.

The method returns an int but it is expected that I will be obtaining huge values. I'm solving this problem in Java.

Here is my code

static int fibonacciModified(int t1, int t2, int n) {

    BigInteger[] f = new BigInteger[n];
    f[0] = BigInteger.ZERO;
    f[1] = BigInteger.ONE;
    BigInteger value = BigInteger.ONE;

    for(int i = 2; i < n; i++) {
        f[i] = f[i-1].multiply(f[i-1]).add(f[i-2]);
        value = f[i];
    }

    return value.intValue();
}

I'm failing the test case when t1 = 0, t2 = 1, n = 10. My output is -1022889632. The correct answer is 84266613096281243382112. If I change the method to return a BigInteger then I do get the right answer.

Edit: This is the link to the problem https://www.hackerrank.com/challenges/fibonacci-modified/problem

1 Answers

You cannot, the maximum value for int is 2,147,483,647 (32 bits of value). If you need big numbers you must use the appropriate variable type.

If for some reason you want to avoid BigInteger at all and your are not going to do any arithmetic operation later, you can always return a String


About the hackerrank problem, just modify the result variable type to BigInteger. Actually, they seem to be aware of the 32/64 bits issue... they are using a String value to prevent it. enter image description here

There's no reason to keep the whole code-template structure. They just care about input/output. You are allowed to modify EVERYTHING but those two things.

This is their input: enter image description here

This is their output (here you can see their output is expected to be a String): enter image description here

Related