Question

I'm new to programming and need help in C. I am writing a program to generate a Fibonacci sequence for values with up to 1000 digits.

Here is my code:

#include <stdio.h>

int main(void)
{
    int seq[1000];
    int i,n;

    printf("How many Fibonacci numbers do you want?: ");
    scanf("%d",&n);

    seq[0] = 0;
    seq[1] = 1;

    for(i = 2; i < n; i++)
        seq[i] = seq[i-1] + seq[i-2];

    for (i = 1; i < n; i++)
        printf("%d: %d\n", i, seq[i]);

    return 0;
}

Now the problem is, the numbers are all correct up until the 47th number. Then it just goes crazy and there's negative numbers and its all wrong. Can anyone see the error in my code? Any help is greatly appreciated.

Était-ce utile?

La solution

I am writing a program to generate a Fibonacci sequence for values with up to 1000 digits.

Not yet you aren't. You are storing the values in variables of type int. Commonly such variables are 32 bit values and have a maximum possible value of 2^31 - 1. That equals 2,147,483,647 which is some way short of your goal of reaching 1,000 digits.

The 47th Fibonacci number is the first number to exceed 2,147,483,647. According to Wolfram Alpha, the value is 2,971,215,073.

When your program attempts to calculate such a number it suffers from integer overflow, because the true value cannot be stored in an int. You could try to analyse exactly what happens when you overflow, why you see negative values, but it really doesn't get you very far. Simply put, what you are attempting is clearly impossible with int.

In order to reach 1,000 digits you need to use a big integer type. None of the built-in types can handle numbers as large as you intend to handle.

Autres conseils

The comment I posted above has the simple answer, but here's a more complete version: C often represents integers with a sequence of 32 bits, and the range of values they can take on are from -2,147,483,648 to 2,147,483,647.

Notice what the 47th Fibonacci number is? 2,971,215,073

After they overflow, they wrap around to the smallest integer possible; see 2's complement notation for more information!

For a solution, I might suggest a BigInteger structure. But Fibonacci numbers get huge really fast, so I'm not sure you'd really want to calculate that many.

you are not using the correct data type; fibonacci numbers tend to grow really fast. So you probably are going beyond the limit for int: 2^31. Since int and long are both 32 bit integers (in most cases ->gcc and VS) try using long long .

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top