Search code examples
c++unsigned-integernegative-integer

Unsigned long long Fibonacci numbers negative?


I've written a simple Fibonacci sequence generator that looks like:

#include <iostream>

void print(int c, int r) {
    std::cout << c << "\t\t" << r << std::endl;
}

int main() {
    unsigned long long int a = 0, b = 1, c = 1;
    for (int r = 1; r <= 1e3; r += 1) {
        print(c, r);
        a = b;
        b = c;
        c = a + b;
    }
}

However, as r gets around the value of 40, strange things begin to happen. c's value oscillate between negative and positive, despite the fact he's an unsigned integer, and of course the Fibonacci sequence can't be exactly that.

What's going on with unsigned long long integers?

Does c get too large even for a long long integer?


Solution

  • You have a narrowing conversion here print(c, r); where you defined print to take only int's and here you pass an unsigned long long. It is implementation defined.

    Quoting the C++ Standard Draft:

    4.4.7:3: If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.

    But what typically happens is that: from the unsigned long long, only the bits that are just enough to fit into an int are copied to your function. The truncated int is stored in Twos complements, depending on the value of the Most Significant Bit. you get such alternation.

    Change your function signature to capture unsigned long long

    void print(unsigned long long c, int r) {
        std::cout << c << "\t\t" << r << std::endl;
    }
    

    BTW, see Mohit Jain's comment to your question.