Why am i not able to print 47th fibonacci number correctly?

前端 未结 4 1618
梦如初夏
梦如初夏 2021-01-29 16:40

I am using 64 bit operating system ,then also i am not able to print 46th fibonacci number correctly which is less than 4 billion.

#include
#inclu         


        
4条回答
  •  Happy的楠姐
    2021-01-29 17:09

    Using Rishikesh Raje's counting system (i.e. 1st Fibonacci is 1) where F(48) is 4807526976, then you weren't able to get F(47) 2971215073 because, as @kaylum commented, you used a signed integer array to hold your values which you need to change to unsigned, and well as change your printf statement to print an unsigned. This would allow you to reach the limit of 32 bit arithmetic:

    #include 
    
    #define LIMIT (50)
    
    int main(void) {
        unsigned int array[LIMIT] = {0, 1};
    
        printf("%u\n", array[0]);
        printf("%u\n", array[1]);
    
        for (size_t i = 2; i < LIMIT; i++)
        {
            array[i] = array[i - 1] + array[i - 2];
            printf("%u\n", array[i]);
        }
    
        return 0;
    }
    

    To get beyond 32 bits, you can switch to long, or long longs as Rishikesh Raje suggests, but work with unsigned variants if you want to reach the maximum result you can with a given number of bits.

提交回复
热议问题