0

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!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
BeatoJeronimo
  • 37
  • 1
  • 4

3 Answers3

0

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.

Ryan
  • 2,058
  • 1
  • 15
  • 29
0

Ryan is correct - after reaching the max limit for int, it will go negative. The code you posted is going to print the first n+1 Fibonacci numbers (You are starting at 0 and going to 70 = 71 numbers). The 71st Fibonacci number is 308,061,521,170,129 which is way over the limit for int.

Instead of using int, use long which has a max limit of 9,223,372,036,854,775,807 which will at least get you to n=91 (first 92 Fibonacci numbers - up to 7,540,113,804,746,346,429).

Michael Norgren
  • 750
  • 6
  • 11
0

You can try this code, and you will get an accpet.

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

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

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