alim - 1 year ago 49

C Question

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?

Answer Source

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;
}
```