I am writing a program to calculate Fibonacci numbers, it has to work by adding the previous binary numbers up to n to get Fibonacci(n), my program is working, but only for Fib(0) -> Fib(45) and this is using Fib(0)=1, fib(1)=1, fib(n)=fib(n-1)+fib(n-2). I am storing the binary numbers in vector<int>, and computeing from there, can anyone think of something that is causing it to create uncorrect numbers past 45?
This is a more compleate discription of the problem that I am having, I didn't have much time when I first posted;
I have to do the computation in binary, so I first take in the number from the user of the index of the fibonacii number that they want to compute, I then take that and convert it to binary, create 3 vectors, fib1, fib2, and fib, initialize fib 1 and 2 to 1, then loop from 0 to the users number { add fib 1 and 2, which are binary numbers to create the next number in the sequence, then store Fib 1 in Fib 2 and the number just calculated in Fib1, } Fib1 when that loop is done will be the answer to the problem in binary, now I have to convert that into decimal, I do this by the following code
This Code is my binary class that has all of the methods needed to do on binary numbers, and adding vectors of ints.
when I run the program with any number under 45, I get the correct number, but if I run 46, I get 823731425
when the correct number is 2971215073, also please remember that this has Fib(0) = 1 not 0.
std::numeric_limits<int>::max()==2147483647 in my system. That is about 231-1.
Now, suppose that bin has a really big number, so its size is greater than 31 (like 33)
1 2 3 4
//for(int i=(bin.size()-1); i>=0; --i){
// temp=bin[i]*pow(2,i);
//in the first iteration
temp = 1*pow(2,33) ; //about 8589934592
That doesn't fit in. It causes overflow and now temp has an useless value.
Then you will be having troubles with the 97th Fibonacci (just a guess).
You need to change the conversion from base 2 to base 10. Check that bignum link for something better than