-1

I have a question about a program which generate Fibonacci numbers. The user enters the number of Fibonacci numbers he/she need , and the program generates it. The problem is after 48 numbers the program start to give wrong numbers. It seems to do trimming to numbers giving out some random results. I made an array of "unsigned long long int" that is 64 bits for each number. It should carry big numbers, but it didn`t.

Here is my code :

‪#‎include‬ <stdio.h>
int main (void)
{
 int n , i ;
 printf("Enter number of Fibonacci numbers you need : ");
 scanf("%d" , &n);

 unsigned long long int fib_numbers[n];

 fib_numbers[0] = 0 ;
 printf("1. %llu\n",0);
 fib_numbers[1] = 1 ;
 printf("2. %llu\n",1);

 for(i=2;i<n;i++)
   {
    fib_numbers[i]=fib_numbers[i-1]+fib_numbers[i-2];
    printf("%d. %llu\n",i+1,fib_numbers[i]);
   }
 return 0;
}

Hers is a snap for output, notice number 49

enter image description here

too honest for this site
  • 12,050
  • 4
  • 30
  • 52

2 Answers2

2

This is definitely a problem with the underlying libraries not supporting a 64bit unsigned long long. Your code works perfectly on my 64bit Linux system.

48. 2971215073
49. 4807526976
50. 7778742049
51. 12586269025
52. 20365011074
53. 32951280099
54. 53316291173
55. 86267571272
56. 139583862445
57. 225851433717
58. 365435296162
59. 591286729879
60. 956722026041

As for a solution, that depends on your platform, compiler, etc. Not enough info to guide. However, you might want to look into a system that supports larger numbers, as 64bits only covers up to fib 94. The GNU Multiple Precision Arithmetic Library might do what you need for longer runs, and may automatically correct for the lack of precision in your libraries as well.

Alderin
  • 150
  • 1
  • 8
-1

You can determine the maximum value of an object of type unsigned long long int the following way

#include <limits>

//...

std::cout << std::numeric_limits<unsigned long long int>::max() << std::endl;

You can compare the value with the values of the Fibonacci numbers you get.

Or in C you can use constant ULLONG_MAX declared in header <limits.h>

Maybe the reason is that the function printf of your compiler does not support format specifier %llu

You can also try to use macro PRIu64 that might be declared in header <inttypes.h>.

For example

#include <inttypes.h>

//...

printf("%d. %" PRIu64 "\n",i+1,fib_numbers[i]);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335