mardi 3 août 2021

C++ Nth Fibonacci Number Big Number Operation Problem

I am working on the function that counts the Nth Number from the Fibonacci sequence.

I am using that algorithm to calculate it: https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula

The problem is that I'm working on the big numbers and I have no idea how to store the data to prevent it from miscalculations and other errors :/

I saw some posts on stack and people suggest to divide the numbers into parts and calculate it that way - I think this is just a temporary and kinda primitive solution.

Is there any new, modern and not so complicated method of storing big numbers and operating (include math operations) on them without any errors??

Here's the Function:

std::string fibonacci(int n)
{

   long double numb = 1 / sqrt(5) * (pow(((1 + sqrt(5)) / 2),n) - pow(((1 - sqrt(5)) / 2),n));

   return std::to_string(numb);

}

Here's the output how the results change:

Input:  40
Output: 102334155.000000
Answer: 102334155
    
Input:  50
Output: 12586269025.000021
Answer: 12586269025

Input:  60
Output: 1548008755920.002930
Answer: 1548008755920

Input:  70
Output: 190392490709135.437500
Answer: 190392490709135

Input:  80
Output: 23416728348467744.000000
Answer: 23416728348467685

Input:  90
Output: 2880067194370825216.000000
Answer: 2880067194370816120

Input:  100
Output: 354224848179263111168.000000
Answer: 354224848179261915075

Aucun commentaire:

Enregistrer un commentaire