简体   繁体   中英

Changing function from returning long to BigInteger

I'm working on a program that finds Fibonacci numbers. The first version of the homework asked for long datatype to be returned and now we have to change our function to return BigInteger. I'm not sure how to change my function to send back BigInteger type. Here is what I have:

public static BigInteger fibonacci_Loop(int f) {
    BigInteger previous, current;

    for(int i = 0; i < f; i ++) {
        BigInteger sum = previous.add(current);
        previous = current;
        current = sum;
    }
    return previous;
}

It won't run because it wants me to initialize previous and current and any time I do it doesn't return the right numbers. I'm not completely sure on how to use BigInteger and any advice would be greatly appreciated.

Below code works for me. Initialize previous to Zero and current to 1 and run the loop likewise. Note that the loop is run one less than the desired fibnacci index.

public static BigInteger fibonacci_Loop(int f) {
BigInteger previous = BigInteger.ZERO;
BigInteger current = BigInteger.ONE;

for(int i = 0; i < f-1; i ++) {
    BigInteger sum = previous.add(current);
    previous = current;
    current = sum;
}
return previous;

}

You can use the constructor that takes a String:

BigInteger i = new BigInteger(“0”);

But there are constants provided you can use:

BigInteger previous = BigInteger.ZERO;
BigInteger current= BigInteger.ONE;

When you're working with longs, they are either a primitive or boxed type so they default to 0 when declared.

java.math.BigInteger however is an Object so you have to initialize it before you use it.

Changing this line BigInteger previous, current; to BigInteger previous = new BigInteger("0"), current = new BigInteger("1"); should fix it.

Rule : First of all you need to initialize any variable declared inside of a function before performing any operation on it.

change our function to return BigInteger

If you only have to return BigInteger then should have only changed the return statement of your previous function with long to

return new BigInteger(previous);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM