I'm playing with a simple program to learn about recursion. I've tried to calculate the Fibonacci number 50 which should be 12,586,269,025.
The result however is 18,446,744,073,410,918,753. Fibonacci numbers between 0 and 46 are calculated correctly, 47 is the first one to be wrong.
The limits have been tested as
LLONG_MAX = 9,223,372,036,854,775,807
ULLONG_MAX = 18,446,744,073,709,551,615
The result is just below ULLONG_MAX.
(All commas inserted manually for readability.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <cmath>
#include <climits>
#include <cstdint>
using namespace std;
int fib(unsigned long long int n){
unsigned long long int r;
if (n>=3){
r = fib(n-1) + fib(n-2);
} else {
r = 1;
}
return r;
}
int main(int argc, char *argv[]){
if (argc==1){
return 1;
}
long long int m = atoll(argv[1]);
unsigned long long int n = m;
unsigned long long int r = fib(n);
cout << r << endl;
return 0;
}
|