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()
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
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&
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()
Related
I'm trying to write a program to find sum of first N natural numbers i.e. 1 + 2 + 3 + .. + N modulo 1000000009
I know this can be done by using the formula N * (N+1) / 2 but I'm trying to find a sort of recursive function to calculate the sum.
I tried searching the web, but I didn't get any solution to this.
Actually, the problem here is that the number N can have upto 100000 digits.
So, here is what I've tried until now.
First I tried splitting the number into parts each of length 9, then convert them into integers so that I can perform arithmetic operations using the operators for integers.
For example, the number 52562372318723712 will be split into 52562372 & 318723712.
But I didn't find a way to manipulate these numbers.
Then again I tried to write a function as follows:
def find_sum(n):
# n is a string
if len(n) == 1:
# use the formula if single digit
return int(int(n[0]) * (int(n[0]) + 1) / 2)
# I'm not sure what to return here
# I'm expecting some manipulation with n[0]
# and a recursive call to the function itself
# I've also not used modulo here just for testing with smaller numbers
# I'll add it once I find a solution to this
return int(n[0]) * something + find_sum(n[1:])
I'm not able to find the something here.
Can this be solved like this?
or is there any other method to do so?
NOTE: I prefer a solution similar to the above function because I want to modify this function to meet my other requirements which I want to try myself before asking here. But if it is not possible, any other solution will also be helpful.
Please give me any hint to solve it.
Your best bet is to just use the N*(N+1)/2 formula -- but using it mod p. The only tricky part is to interpret division by 2 -- this had to be the inverse of 2 mod p. For p prime (or simply for p odd) this is very easy to compute: it is just (p+1)//2.
Thus:
def find_sum(n,p):
two_inv = (p+1)//2 #inverse of 2, mod p
return ((n%p)*((n+1)%p)*two_inv)%p
For example:
>>> find_sum(10000000,1000000009)
4550000
>>> sum(range(1,10000001))%1000000009
4550000
Note that the above function will fail if you pass an even number for p.
On Edit as #user11908059 observed, it is possible to dispense with multiplication by the modular inverse of 2. As an added benefit, this approach no longer depends on the modulus being odd:
def find_sum2(n,k):
if n % 2 == 0:
a,b = (n//2) % k, (n+1) % k
else:
a,b = n % k, ((n+1)//2) % k
return (a*b) % k
Anyone know the most efficient way of displaying the first 100 numbers in the Fibonacci Sequence in Python please?
Here is my current code:
fib1,fib2,fib3= 0,0,1
while fib3< 100:
print(fib3)
fib1=fib2
fib2=fib3
fib3=fib1 + fib2
Understand the working of python and fibonacci Sequence. Use generator feature of python. Follow the code
a = int(input('Give num: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
According to the Fibonacci formula, here's a way to get the nth member of the Fibonacci sequence.
This function doesn't use loops nor recursion (recursions are horrible in Python, they are always slower than an iterative solution, because of how Python handle recursion, see here for more info about it)
I'm currently learning Python on repl.it and I have a problem with one of my work.
My code is supposed to:
1.Input a given integer X
2.Find the greatest integer n where 2ⁿ is less than or equal to X.
3.Print the exponent value(n) and the result of the expression 2ⁿ.
But my code fail as the machine insert too big number like 10^8+2. The program completely failed
Here is the piece of code that I'm working on:
X = int(input())
a = X//2
while a > -1:
if (2**a) < =x:
print(a)
print(2**a)
break
else:
a -= 1
Can anyone find me another solution to this problem, or improve the bit of code I'm working on by its runtime? It works with small number(less than 10^6) but otherwise the program freeze.
Thanks in advance!
Of course, I can't refer to the "too big input" that you mention (since you didn't provide it), but as for the problem itself, it could be easier solved in the following way:
import numpy as np
a = int(np.log2(your_input))
The first issue I see is that in you code
if (2**a) < =x:
print(a)
print(2**a)
you calculate the value of 2**a twice. A good start could be to save the value of 2**a into a variable. However, since you are only doing powers of 2 you could also take a look at bitwise operations. So instead of doing a = X//2 you could also write
a= X >> 2
and instead of doing 2**a write
temp = 1 << a
When working with powers of 2 it can be significantly faster to work with bitwise operations.
I did it! (using some of your solutions of course)
This is my teachers code :
x = int(input())
n = 1
while 2 ** n <= x:
n += 1
print(n - 1, 2 ** (n - 1))
Like if i told the program n=10, how would I make it return 10*9*8*7*6*5....1?
I thought a while loop but I feel I messed up somewhere because it doesn't sum up all of the numbers in the sequence.
My current code looks like this
def product(n):
i=n
a=n-1
while a>0:
return i * a
b=i * a
a=a-1
i=i-1
Are there any better ways to do it without using recursion? Sorry for the incredibly beginner question, but I'm trying to teach myself how to code. You gotta start somewhere!
Thanks!
Since you are trying to learn to code, I won't give you a total solution, but
I'll give you a few hints instead:
Have a for loop that runs up from 1 to n (using range(1, n+1)) instead of your while-loop. This will generate the values that you want to multiply and iterate the right number of times (which can be a bit tricky with while loops sometimes).
Have a variable named product to store the result of the multiplications each time through the loop.
Initialize product before you enter the for-loop. Once inside you'll be just updating the value of product.
After you are done with the loop, you can use the return statement to return the value of product.
Finally, for testing purposes, you may want to start out with a small value of n, like 4, and print out the values you are computing inside the loop to verify how your code is working.
There are more terse and pythonic ways to do this, but this uses the code structure you have already set up. And of course recursively as well as you mention too.
Once you master the basics, you'll appreciate the more idiomatic ways of writing this, or calling the appropriate functions that do this for you.
Well, here's another Pythonic approach.
>>> import operator
>>> numbers = range(1, 11)
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> reduce(operator.mul, numbers)
3628800
Assuming you what you meant is factorial function, you can simply just use the math.factorial():
>>> import math
>>> math.factorial(10)
3628800
You are trying to find the factorial of a number n, essentially. For finding the factorial of a number, there are 2 methods
Using a Loop structure
Using Recursion (as you've mentioned)
As a new programmer, you would be better off with a simple loop structure that runs from 1 to n and puts the multiplied value at each iteration into a variable. That variable is your answer. But also know that recursion will also work and make the code look elegant. Happy Programming !
This is called the factorial. 10! is equivalent to 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
def factorial(n):
product = 1
while n > 0:
product *= n
n -= 1
return product
By the way, in practice, just use math.factorial.
def factorial(n):
if n <= 1: return 1
return n * factorial(n-1)
I always think of factorial as the quintessential example in learning recursion ...
Another way to do this is to use scipy.product.
>>> import scipy
>>> scipy.product(xrange(1,11))
3628800
As a learner you should do it without using any inbuilt functions it will help you to learn programming rather just tool as learning a tool is much easier one you become good programmer. there are two ways of doing this I have implemented simpler versions.
Using Recursion:
def product(n):
if n== 1:
return 1
return n * product(n-1)
Using Simple Loop:
def product(n):
res = 1
while n>1:
res = res * n
n = n - 1
return res
For factorials too large to compute directly, there is another way to do that by using the Stirling's approximation.
n! := sqrt(2πn)*(n/e)^n, where e = 2.71828
Hi I have been trying out this problem:
Suppose P(n) is sum of digits of 2^n
For example:
As 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26,so P(15)=26.
Catulate sum of the P(n) for n=1 to 10000.
Here is my python code which is giving 67783431 as answer but the judge doesn't seems to be agree on this:
def P(n):
n = int(1<<n)
S = 0
while n != 0:
S += (n%10)
n /= 10
return S
Sum = 0
for i in range(1,10001):
Sum += P(i)
else:
print(Sum)
Could anybody tell me what's wrong in my approach? I would be appreciate if somebody points me to a mathematical solution for the same.
If you had shown the comments, you would've noticed that the site owners, or problem maintainer, is a moron.
He meant to say from "0 to 10000", not "1 to 10000", but apparently the problem cannot be edited, or the maintainer don't want to do it.
The sum is off by 1 since 1<<0 is 1, which adds 1 to the sum.
Try submitting 67783432.
Note: I realize that calling the site owners or the maintainer a moron might sound harsh, but when posting content on a site about "Mathematics", accuracy is kinda important. Having such a site without the ability, or the requirement, to fix wrong problems, seems kinda stupid to me.
A more elegant solution in terms of functional programming might be:
>>> P = lambda n: sum(map(int, str(1 << n)))
>>> sum(P(i) for i in xrange(10001))
67783432
(Notice this computes the sum of P(i) for i=0 to 10000.)
Your solution takes quite some time to run (more than a minute, anyway). Is there a time limit imposed by the judge on the length of time solutions can take to run?
Also, if you're using Python 3, then the division operator (/=) always produces a floating point result. In Python 2, the result would be truncated to an integer with integer inputs.
Actually, with Python 3 I get an overflow error:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 6, in P
OverflowError: int/int too large for a float
Here's an alternative implementation that confirms your answer is correct:
>>> sum(reduce(lambda x, y: x + int(y), str(2**n), 0) for n in xrange(1, 10001))
67783431
Or one that memoizes:
>> reduce(lambda x, y: (sum(int(c) for c in str(x[1]*2)) + x[0], x[1]*2), xrange(0, 10000), (0,1))[0]
67783431
Actually, since Java cannot produce such large numbers (unless you use BigInteger class - which I have never used ), its better if you use flexible languages like Python
Python gave me 2**1000. its a very huge number whose solution is 1366
try this in python
a = 2**1000
print( a )
then take the output from python as a string and take sum each digit