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,
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)
etc. spends 8 characters ,t=5**.5
to gain 12: three lots of 5**.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 of 2**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)
.
Here is the 110 solution, I had to rewrite the formula though and used @Gareth's suggestion:
p=5**.5
f=lambda n:((1+p)**n-(1-p)**n)/(2**n*p)
exec "n=input();print int(f(n+11)-f(n+1)+f(n+6)%10);"*input()
Saving another symbol, 109 now (manipulating with n
and getting rid of +11
):
p=5**.5
f=lambda n:((1+p)**n-(1-p)**n)/(2**n*p)
exec "n=input()+6;print int(f(n+5)-f(n-5)+f(n)%10);"*input()
Edit: New way to calculate particular number, saves another 4 symbols and allows to avoid int()
:
def f(n):exec"a=b=1;"+"a,b=b,a+b;"*(n-1);return a
exec "n=input()+6;print f(n+5)-f(n-5)+f(n)%10;"*input()
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:
f[1] = 1;
f[2] = 1;
f[x_] := f[x] = f[x - 1] + f[x - 2]
t = 0;
n = 35;
For[i = 0, i <= 9, i++, t += f[n + i]]
t += f[n + 246] ~Mod~ 10
Or, in terse Mathematica, still without using Fibonacci
function:
f[1|2]=1;a:f@x_:=a=f[x-1]+f[x-2];Sum[f[#+x],{x,0,9}]+f[#+246]~Mod~10&
p=5**.5
f=lambda n:((1+p)**n-(1-p)**n)/(2**n*p)
exec"n=input();print 55*f(n)+88*f(n+1)+f(n+6)%10;"*input()
106 chars as long you don't care about int() function and accept a float
This one prints the Fibonacci series up to n.
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.