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
Related
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))
This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 5 months ago.
I am a complete python beginner and I am trying to solve this problem :
A number is called triangular if it is the sum of the first n positive
integers for some n For example, 10 is triangular because 10 = 1+2+3+4
and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
to find the smallest 6-digit triangular number. Enter it as your
answer below.
I have written this program:
n = 0
trinum = 0
while len(str(trinum)) < 6:
trinum = n*(n+1)/2
n += 1
print(trinum)
And it only works in the python I have installed on my computer if I say while len(str(trinum)) < 8: but it is supposed to be while len(str(trinum)) < 6:. So I went to http://www.skulpt.org/ and ran my code there and it gave me the right answer with while len(str(trinum)) < 6: like it's supposed to. But it doesn't work with 6 with the python i have installed on my computer. Does anyone have any idea what's going on?
Short Answer
In Python 3, division is always floating point division. So on the first pass you get something like str(trinum) == '0.5'. Which isn't what you want.
You're looking for integer division. The operator for that is //.
Long Answer
The division operator changed in Python 2.x to 3.x. Previously, the type of the result was dependent on the arguments. So 1/2 does integer division, but 1./2 does floating point division.
To clean this up, a new operator was introduced: //. This operator will always do integer division.
So in Python 3.x, this expression (4 * 5)/2 is equal to 10.0. Note that this number is less than 100, but it has 4 characters in it.
If instead, we did (4*5)//2, we would get the integer 10 back. Which would allow your condition to hold true.
In Python 2, the / operator performs integer division when possible: "x divided by y is a remainder b," throwing away the "b" (use the % operator to find "b"). In Python 3, the / operator always performs float division: "x divided by y is a.fgh." Get integer division in Python 3 with the // operator.
You have two problems here, that combine to give you the wrong answer.
The first problem is that you're using /, which means integer division in Python 2 (and the almost-Python language that Skulpt implements), but float division in Python 3. So, when you run it on your local machine with Python 3, you're going to get floating point numbers.
The second problem is that you're not checking for "under 6 digits" you're checking for "under 6 characters long". For positive integers, those are the same thing, but for floats, say, 1035.5 is only 4 digits, but it's 6 characters. So you exit early.
If you solve either problem, it will work, at least most of the time. But you really should solve both.
So:
n = 0
trinum = 0
while trinum < 10**6: # note comparing numbers, not string length
trinum = n*(n+1)//2 # note // instead of /
n += 1
print(trinum)
The first problem is fixed by using //, which always means integer division, instead of /, which means different things in different Python versions.
The second problem is fixed by comparing the number as a number to 10**6 (that is, 10 to the 6th power, which means 1 with 6 zeros, or 1000000) instead of comparing its length as a string to 6.
Taking Malik Brahimi's answer further:
from itertools import *
print(next(dropwhile(lambda n: n <= 99999, accumulate(count(1))))
count(1) is all the numbers from 1 to infinity.
accumulate(count(1)) is all the running totals of those numbers.
dropwhile(…) is skipping the initial running totals until we reach 100000, then all the rest of them.
next(…) is the next one after the ones we skipped.
Of course you could argue that a 1-liner that takes 4 lines to describe to a novice isn't as good as a 4-liner that doesn't need any explanation. :)
(Also, the dropwhile is a bit ugly. Most uses of it in Python are. In a language like Haskell, where you can write that predicate with operator sectioning instead of a lambda, like (<= 99999), it's a different story.)
The division method in Py2.x and 3.x is different - so that is probably why you had issues.
Just another suggestion - which doesn't deal with divisions and lengths - so less buggy in general. Plus addition is addition anywhere.
trinum = 0
idx =0
while trinum < 99999: #largest 5 digit number
idx += 1
trinum += idx
print trinum
import itertools # to get the count function
n, c = 0, itertools.count(1) # start at zero
while n <= 99999:
n = n + next(c)
Dear Stack Exchangers,
I encountered a strange result while attempting to calculate the sum of values in a python dictionary. If my dictionary gets past a certain size, the following function: sum(dict.values()) appears to give incorrect results. It appears that the result becomes suddenly negative for no apparent reason. I am using python 2.7 on Windows 7. (I apologize in advance for my coding style).
Please note that I encountered this behaviour while working on https://projecteuler.net/problem=72, but I am not asking for help to get the answer, I am just perplexed by the behaviour of the built-in function. (I also apologise for posting a partial solution on a public forum, please look away now if you don't want any hints).
The goal of the program is explained on the project Euler link (above), but I will attempt to briefly explain my code:
The first function uses a Sieve of Erasthenes to produce a list of prime numbers and a modified sieve to produce a dictionary of {composite_number:[prime_factor_list]} within a specified range.
The second function attempts to count the number of fractions of the form n/d that can be produced where n < d and d <= 1000000. The problem states that I should only count reduced proper fractions, so the bulk of this function is concerned with weeding out reducible fractions. My strategy is to loop through each numerator between 1 and d-1, and discard unsuitable denominators. For primes this is simple, and for non-primes I am close to a working solution, but still discard some values more than once. For the purposes of this post, the important detail is the way that I tally up the count:
Initially I used a simple counter (initialise count to 0 then increment as needed), but decided to try a dictionary instead. What surprised me was that the two methods gave different results, but only when the upper limit (d) exceeded a certain size. I probed deeper and managed to isolate the exact moment that the counts diverge. The line if 88000 < i < 88055: near the bottom identifies the point at which the sum of dict values begins to differ from the simple count. For values up to i = 88032, the value are the same, but when i = 88033, the values diverge dramatically:
from collections import defaultdict
def primeset(limit):
pr = [0]*(limit+1)
for i in range(2,limit+1):
j = i
i += j
while i <= limit:
pr[i] = 1
i += j
primes = [k for k in range(2,limit+1) if pr[k] == 0]
composites = defaultdict(list)
for p in primes:
q = p
p += q
while p <= limit:
composites[p].append(q)
p += q
return primes, composites
def method2(limit):
primes, composites = primeset(limit)
prf = {}
count = 0
count += limit-1
count += (limit-2)/2
prf[1] = limit-1
prf[2] = (limit-2)/2
for i in primes:
if i != 2:
tally = limit-i-(limit/i)+1
count += tally
prf[i] = tally
for i in composites:
tally = limit-i
for item in composites[i]:
tally -= (limit/item-i/item)
count += tally
prf[i] = tally
if 88000 < i < 88055:
print i, count, tally, sum(prf.values())
return count, prf
result, index = method2(88547)
print result,sum(index.values())
I expect I have done something really stupid, but I felt compelled to put it out there in case something really is amiss.
Regards,
You are having a problem with integer overflow, which in Python is not supposed to happen. You have a 32-bit machine, so the largest normal integer is (2^31 - 1). Once your calculation exceeds that Python should automatically switch to doing calculations using a long which isn't limited in the size of the number that it can support. I only have 64-bit machines, but the same thing applies except the max integer is (2^63 - 1). You can tell from the shell when you have a long because of the L that is printed after the number. Here is an example from my shell:
>>> 2**62 - 1 + 2**62 # This is max int
9223372036854775807
>>> 2**63 # This is a long
9223372036854775808L
>>> num = 2**62 - 1 + 2**62
>>> num
9223372036854775807
>>> num+1
9223372036854775808L
>>> d = {1:2**62,2:-1,3:2**62}
>>> sum(d.values())
9223372036854775807
>>> d = {1:2**62,2:-1,3:2**62,4:1}
>>> sum(d.values())
9223372036854775808L
In my case with Python 2.7 on Linux on a 64-bit machine this all works as expected.
Now I run the same thing using Spyder and I get the wrong answer:
>>> d = {1:2**62,2:-1,3:2**62,4:1}
>>> sum(d.values())
-9223372036854775808
It promotes correctly when I just do normal addition, but this sum from a dictionary gives the wrong answer. This isn't specific to dictionaries, just the sum function. Same thing with an list:
>>> list = [2**62, -1, 2**62, 1]
>>> sum(list)
-9223372036854775808
So the problem is isolated to the sum() function in Spyder and happens for both 32 and 64-bit machines.
The real answer turns out that Spyder automatically imports numpy. Numpy has its own version of the sum function. It is described as follows "Arithmetic is modular when using integer types, and no error is raised on overflow." You are using that version of sum and it is causing the problem. If you don't want to use that sum you can put the following at the top of your file:
from __builtin__ import sum
That will cause the built-in version of sum to be used and you will get the correct answer.
To figure out that sum was not coming from where I thought it was coming from I could have used the following:
>>> import inspect
>>> inspect.getmodule(sum)
<module 'numpy.core.fromnumeric' from '/usr/lib/python2.7/dist-packages/nump/core/fromnumeric.pyc'>
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
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()