print fibo big numbers in c++ or c language

后端 未结 6 1229
夕颜
夕颜 2021-01-16 23:39

I write this code for show fibonacci series using recursion.But It not show correctly for n>43 (ex: for n=100 show:-980107325).

#include
#inc         


        
6条回答
  •  花落未央
    2021-01-17 00:02

    Code overflows the range of the integer used long.
    Could use long long, but even that may not handle Fib(100) which needs at least 69 bits.

    Code could use long double if 1.0/LDBL_EPSILON > 3.6e20

    Various libraries exist to handle very large integers.

    For this task, all that is needed is a way to add two large integers. Consider using a string. An inefficient but simply string addition follows. No contingencies for buffer overflow.

    #include 
    #include 
    #include 
    
    char *str_revese_inplace(char *s) {
      char *left = s;
      char *right = s + strlen(s);
      while (right > left) {
        right--;
        char t = *right;
        *right = *left;
        *left = t;
        left++;
      }
      return s;
    }
    
    char *str_add(char *ssum, const char *sa, const char *sb) {
      const char *pa = sa + strlen(sa);
      const char *pb = sb + strlen(sb);
      char *psum = ssum;
      int carry = 0;
      while (pa > sa || pb > sb || carry) {
        int sum = carry;
        if (pa > sa) sum += *(--pa) - '0';
        if (pb > sb) sum += *(--pb) - '0';
        *psum++ = sum % 10 + '0';
        carry = sum / 10;
      }
      *psum = '\0';
      return str_revese_inplace(ssum);
    }
    
    int main(void) {
      char fib[3][300];
      strcpy(fib[0], "0");
      strcpy(fib[1], "1");
      int i;
      for (i = 2; i <= 1000; i++) {
        printf("Fib(%3d) %s.\n", i, str_add(fib[2], fib[1], fib[0]));
        strcpy(fib[0], fib[1]);
        strcpy(fib[1], fib[2]);
      }
      return 0;
    }
    

    Output

    Fib(  2) 1.
    Fib(  3) 2.
    Fib(  4) 3.
    Fib(  5) 5.
    Fib(  6) 8.
    ...
    Fib(100) 3542248xxxxxxxxxx5075.  // Some xx left in for a bit of mystery.
    
    Fib(1000) --> 43466...about 200 more digits...8875
    

提交回复
热议问题