-1

I am trying to write a program to print Fibonacci numbers, such as

        0 1 1 2 3 5 8 21 ....

last number is sum of previous two.

I thought it is easy, but realized you have to print a huge number such as

   117669030460994

which exceeds size of every available type of numbers in C (just checked them, far exceeds) .

So, how could I able to store and print such big number?

arslan
  • 2,034
  • 7
  • 34
  • 61

2 Answers2

1

I wrote a similar program a while ago which handled unsigned long long integers for the Fibonacci sequence. I'm not sure how efficient it is because I used an array to store the numbers.

I also used the %I64d format specifier for printing the huge 64 bit integers, because I was using windows. But I think if your using linux then %llu is fine.

As @M Oehm pointed out in the comments, using uint64_t from is also a another way of declaring unsigned long long.

This is what it looks like:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define MAX 100

int
main(void) {
    int i, range;

    unsigned long long array[MAX];
    /* or uint64_t from <stdint.h> */

    printf("Enter number range: ");
    if (scanf("%d", &range) != 1) {
        printf("invalid number\n");
        exit(EXIT_FAILURE);
    }

    array[0] = 0;
    array[1] = 1;

    for (i = 2; i < range; i++) {
        array[i] = array[i-1] + array[i-2];
    }

    printf("Fibonacci Series is: ");
    for (i = 0; i < range; i++) {
        printf("%I64d ", array[i]);
    }

    return 0;
}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

What you want is bignums, a.k.a. arbitrary precision arithmetic. There are several libraries for that, notably GMPlib. You'll be able to compute large Fibionacci numbers of several thousands (or even millions) of digits.

Be aware that bignum arithmetic is difficult to implement efficiently. So don't reinvent the wheel, the few simple algorithms you'll think about are less efficient than state of the art. Use an existing library (which often would use some machine instruction like add with carry that speeds up such operation).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547