-1

I am trying to print the first 80 terms of fibonacci series but after certain range numbers appears to be negative.So, is this correct?

Here's the code:

#include <stdio.h>
    int main() {
        int i,first_term=0, second_term=1, next_term;
        for(i=0; i<80; i++)
        {
            printf("%d, ",first_term);
            next_term= first_term + second_term;
            first_term=second_term;
            second_term = next_term;

        }
        return 0;
    }
binbin
  • 11
  • 1

2 Answers2

2

Yes, your formula is correct. However, numbers in the Fibonacci sequence grow quickly, so your ints are overflowing. You can get more correct numbers if you use long instead of int, for example.

#include <stdio.h>

int main(){
    unsigned int i;
    unsigned long long first_term=0, second_term=1, next_term;

    for(i=0; i<80; i++)
    {
        printf("%llu, ",first_term);
        next_term= first_term + second_term;
        first_term=second_term;
        second_term = next_term;
    }

    return 0;
}
Alejandro De Cicco
  • 1,216
  • 3
  • 17
  • 1
    Using `long` assumes that that it's a 64 bit machine. Probably reasonable these days, but `long` on a 32 bit machine is 32 bits. `long long` [and `%lld`] are the way to go. – Craig Estey May 01 '20 at 16:25
  • Thanks for the info, I will update my answer. Don't you think using `unsigned long long` is better? – Alejandro De Cicco May 01 '20 at 16:27
  • 1
    Yes. I assumed you'd catch that, as Mark's comment at the top mentions it (i.e.) you get one extra bit of precision and can't go negative--overflow would be noticing that term N+1 becomes less than term N – Craig Estey May 01 '20 at 16:32
2

This is due to integer overflow.

Fibonacci numbers can't be negative.

I would suggest you to use long long int or unsigned long long int as follows:

#include <stdint.h>

int main() {

    int i;

    uint64_t first_term=0, second_term=1, next_term;

    for(i=0; i<80; i++)
    {
        printf("%llu, ",first_term);
        next_term= first_term + second_term;
        first_term=second_term;
        second_term = next_term;

    }
    return 0;
}

PS: The fibonacci series grows very quickly. There can be overflow again with long long int and even unsigned long long int when numbers cross 18,446,744,073,709,551,615 which is the upper limit of unsigned long long int. Therefore, BigInt for C++ will be beneficial.

Deepak Tatyaji Ahire
  • 4,883
  • 2
  • 13
  • 35