斐波那契数列之和
我在此处找到了此任务。
给定第 i 个 (1<=i<=35) 斐波那契数 number F(i) 计算总和 第 i 到第 i+9 个数字 F(i)+F(i+1)+...+F(i+9) 以及最后一个 第 i+246 位 F(i+246)
我一直在尝试使用 python 和一些技巧(Binnet 的公式和一个棘手的递归)来解决这个问题:
f=lambda n:((1+5**.5)**n-(1-5**.5)**n)/(2**n*5**.5)
exec"n=input();print int(55*f(n)+88*f(n+1)+f(n+6)%10);"*input()
但我还没有设法挤压思想给定的源代码限制是 111,我的是 115,有什么提示如何改进我的解决方案吗?
我是 python 的新手,因此任何能够带来成功解决方案的帮助将不胜感激。
谢谢,
I found this task here.
Given the ith (1<=i<=35) Fibonacci
number F(i) calculate the sum of the
ith till i+9th number
F(i)+F(i+1)+...+F(i+9) and the last
digit of the i+246th one F(i+246)
I have been trying to solve this using python and some tricks(Binnet's formula and a tricky recurrence):
f=lambda n:((1+5**.5)**n-(1-5**.5)**n)/(2**n*5**.5)
exec"n=input();print int(55*f(n)+88*f(n+1)+f(n+6)%10);"*input()
but I didn't yet managed to squeeze thought the give source code limit which is 111 and mine is 115,any hints how to improve my solution?
I am a rather newbie to python so any sort of help resulting in a successful solution will be much appreciated.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您尝试过使用这个求和公式吗?
http://en.wikipedia.org/wiki/Fibonacci_number#Second_identity(“第二身份”)?
Did you try to use this sum formula?
http://en.wikipedia.org/wiki/Fibonacci_number#Second_identity ("Second Identity")?
f = lambda n,t=5**.5:((1+t)**n-(1-t)**n)/(2**n*t)
等。花费 8 个字符,t=5**.5
获得 12:三批5**.5
->t
。这样就节省了 4 个字符,这似乎正是您所需要的。[已编辑以纠正拼写错误;我在分母中使用了
2*n
而不是2**n
。]您可以通过比奈公式的不同变形来保存更多字符:
f= lambda n:round((1+5**.5)**n/5**.5/2**n)
。f = lambda n,t=5**.5:((1+t)**n-(1-t)**n)/(2**n*t)
etc. spends 8 characters,t=5**.5
to gain 12: three lots of5**.5
->t
. That's a saving of 4 characters, which seems to be what you require.[EDITED to correct a typo; I had
2*n
instead of2**n
in the denominator.]You can save a few more characters with a different twist on Binet's formula:
f=lambda n:round((1+5**.5)**n/5**.5/2**n)
.这是 110 的解决方案,我不得不重写公式并使用 @Gareth 的建议:
保存另一个符号,现在 109 (使用
n
进行操作并摆脱+11
) :编辑:计算特定数字的新方法,保存另外 4 个符号并允许避免
int()
:Here is the 110 solution, I had to rewrite the formula though and used @Gareth's suggestion:
Saving another symbol, 109 now (manipulating with
n
and getting rid of+11
):Edit: New way to calculate particular number, saves another 4 symbols and allows to avoid
int()
:106 个字符,只要您不关心 int() 函数并接受浮点数
106 chars as long you don't care about int() function and accept a float
抱歉,我在发帖之前没有正确阅读您的问题。我很高兴你至少发现了它的一些用处。
我不懂 Python,但在 Mathematica 中,尽可能通用:
或者,在简洁的 Mathematica 中,仍然不使用 Fibonacci 函数:
Sorry I did not read your question properly before posting. I am glad you at least found some use in it.
I don't know Python, but in Mathematica, as generic as possible:
Or, in terse Mathematica, still without using
Fibonacci
function:这个打印了直到 n 的斐波那契数列。
This one prints the Fibonacci series up to n.