Print nth Fibonacci number [upto 1000 digits] [closed]

断了今生、忘了曾经 提交于 2020-01-17 14:43:48

问题


How can one calculate nth Fibonacci number in C/C++? The Fibonacci number can contain upto 1000 digits. I can generate numbers upto 2^64 (unsigned long long). Since that is the limit of numbers, so I am guessing there has to be some other way of doing it - which I do not know of.

EDIT:

Also, it has to be done without using any external libraries.


回答1:


I'll give a few hints since you haven't indicated that you've started yet.

A thousand digits is a lot. More than any built-in numeric type in C or C++ can hold.

One way to get around it is to use an arbitrary-precision math library. This will have constructs that will give you basically as many digits as you want in your numbers.

Another way is to roll your own cache-and-carry:

unsigned short int term1[1024];  // 1024 digits from 0-9
unsigned short int term2[1024];  // and another

unsigned short int sum[1024];    // the sum

addBigNumbers(&term1, &term2, &sum);   // exercise for the reader

I'd expect the algorithm for addBigNumbers to go something like this:

Start at the ones digit (index 0)
Add term1[0] and term2[0]
Replace sum[0] with the right digit of term1[0] + term2[0] (which is ... ?)
Keep track of the carry (how?) and use it in the next iteration (how?)
Repeat for each digit

Now, since you're calculating a Fibonacci sequence, you'll be able to re-use these big numbers to get to the next term in the sequence. You might find that it's faster not to copy them around but to just change which ones are the terms and which one is the sum on your repeated calls to addBigNumbers.




回答2:


You could try using GMP for arbitrarily large integers.



来源:https://stackoverflow.com/questions/19449994/print-nth-fibonacci-number-upto-1000-digits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!