javanumbersfibonacciacm-java-libraries

Fibonacci's Code with ACM Library


Hello i have a question about this code i've found in this page. I have already done the Fibonacci by my own but i think this is better. The idea is that you have to choose "n" and the code works until you reach n. It works with the first numbers, but i dont know why when i choose for example n = 70 there are negative numbers!! I dont know why this hapens but i can't resolve it, and im trying to resolve all the exercises of my book because the methods are hard to me. Sory for my poor english.

public class NewFibonacci extends ConsoleProgram {
 int a = 0;
 int b = 1;

public void run() {
    int n = readInt ("n: ");
    for(int i = 0; i <= n; i++) {
        println (fibonacci (n));
    }
}

private int fibonacci(int n) {
    int c = a + b;
    a = b;
    b = c;
    return c;
}
}           

Thank you!


Solution

  • An int is limited to a certain number of bits. If you are using Java, then an int can hold 32 bits (range is from -2,147,483,648 to 2,147,483,647). Once the Fibonacci numbers get higher than the max value of an int, you're going to start seeing negative values.