0

Problem I am solving a fibonacci problem where user enters any index and I have to get the fibonacci number of that index. My code is working just fine for small number 0-80 but after that the code does not output the exact fibonacci number

Example: The fibonacci of 100 will be 354224848179261915075 and I am getting 354224848179261800448. I used bigint in c++ to store the answer. Precision is important because I just need last 5 bits of my answer.

Here is my code

int n;
cin>>n;
setprecision(18);
double term1=(1+sqrt(5))/2;
double term2=(1-sqrt(5))/2;

double ans = (1/sqrt(5))*(pow(term1, n)-pow(term2, n));


std::cout << std::fixed << ans2<<endl;

Sorry I'm not good in English.

klutt
  • 25,535
  • 14
  • 43
  • 72
  • 2
    You say you *stored* the answer in some bigint, but what we see here is a calculation in `double` (which has limited precision as per the duplicate). – DevSolar Nov 30 '17 at 13:36
  • Oh, and I hope you're not using those last 5 bits as input for some cryptography function... – DevSolar Nov 30 '17 at 13:38
  • @DevSolar I tried saving the answer in bigint also. I doesn't work for me. – Raja Ahsan Nov 30 '17 at 13:40
  • 3
    Then open a new question showing the bigint-using code. (Besides, what "bigint" are you referring to? Because the C++ standard knows no such thing.) Be aware though, as long as you do even one of the store/calculation steps in `double` (e.g. `sqrt()`, `pow()`), you are bound by limited precision. – DevSolar Nov 30 '17 at 13:42
  • You have to *compute* the bigint, transferring the already inaccurate `double` can't save it. – Weather Vane Nov 30 '17 at 13:44
  • 1
    Sidenote: You didn't check if `n` was read successfully. ;-) – DevSolar Nov 30 '17 at 13:46
  • @DevSolar I'm getting correct answers upto 80. That means 'n' was read successfully. right? – Raja Ahsan Nov 30 '17 at 13:48
  • @RajaAhsan: You are reading from `cin`. Your user might have entered a letter, which (in C++98) would result in `cin`'s failbit being set *and `n` being left uninitialized*. (C++11 changed this to `n` being set to zero.) Always cater for malformed input. But this is just a sidenote unrelated to your problem. – DevSolar Nov 30 '17 at 13:50
  • 1
    That you're getting correct answers up to 80 is because only then does the result get more digits than `double` can hold without loss of precision. – DevSolar Nov 30 '17 at 13:52
  • 1
    "I just need last 5 bits of my answer." If this is true, to solve this task 1) do not use `double` 2) do not use bigint 3) Instead, iterate the terms `f(n) = f(n-1 + f(n-2)`,_but code only needs to keep the least 5 bits_. The upper bits are irrelevant. – chux - Reinstate Monica Nov 30 '17 at 15:44

0 Answers0