打印第n个Fibonacci数[1000高达位数] [英] Print nth Fibonacci number [upto 1000 digits]

查看:306
本文介绍了打印第n个Fibonacci数[1000高达位数]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何之一的 C / C ++计算第n个斐波纳契数?斐波那契数可以包含高达1000位。我可以高达生成数字2 ^ 64(无符号long长)。自认为是数字的限制,所以我猜测,必须有做的一些其他的方式 - 我不知道

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.

编辑:

此外,它具有不使用任何外部库来完成。

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

推荐答案

因为你还没有表明你还没有开始,我给一些提示。

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

一个千位数是很多。比任何内置于C或C ++可以容纳的数值类型。

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

绕过它的一种方法是使用一个arbitrary- precision数学库。这将对构建正如你在你的号码想,这将使你基本上尽可能多的数字。

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

我期望为 addBigNumbers 算法去是这样的:

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

现在,因为你计算斐波纳契数列,你就可以重新使用这些大数字去序列中的下学期。你可能会发现,它的速度不是围绕复制它们,而是只需要改变哪些条款,其中之一就是 addBigNumbers 您重复调用的总和。

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.

这篇关于打印第n个Fibonacci数[1000高达位数]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆