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

前端 未结 4 1577
梦如初夏
梦如初夏 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条回答
  • 2021-01-29 16:58

    Either Use an unsigned integer array or for more higher values use unsigned long long long array but you don't need an array to print fibonacci series you can simply do this:-

    void main()
    {
      unsigned long long i=1, num1=1, num2=0;
      printf("1 \n");
      for(i; i<100 ; i++)
       {
         num1=num1+num2;
         num2=num1-num2;
         printf("%lli \n", num1);
       }
      getch();
     }
    
    0 讨论(0)
  • 2021-01-29 16:59

    You have to use long long as your data type of the array. because You are going to store out-range numbers of the integer range.(-2,147,483,648 to 2,147,483,647) And declaration of int i should be before the for loop.

    #include<stdio.h>
    
    int main(void)
    {
    
        int n=50;
        long long array[n];
        array[0]=0;
        array[1]=1;
        printf("%lli\n",array[0]);
        printf("%lli\n",array[1]);
        int i;
        for(i=2;i<n;i++)
        {
            array[i]=array[i-1]+array[i-2];
            printf("%lli\n",array[i]);
        }
    }
    
    0 讨论(0)
  • 2021-01-29 17:03

    i am not able to print 46th fibonacci number correctly which is less than 4 billion.

    You are most probably going out of range of an integer, which is from -4294967296 to 4294967295.

    Change int array[n]; to long long array[n];

    Also, the printf's should be changed from %i to %lli

    Edit : On running the numbers, you get expected value of F(48) as 4807526976 which is out of range of an integer.

    0 讨论(0)
  • 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 <stdio.h>
    
    #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.

    0 讨论(0)
提交回复
热议问题