Summing up the numbers!

Hi, I tried this problem :

Suppose that P (n) is the sum of the digits 2 ^ n For example:
With 2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26, therefore P (15) = 26.
Make up the sum of P (n) for n = 1 to 10000.

Here is my python code that gives 67783431 as an answer, but the judge does not seem to agree with 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) 

Can someone tell me what's wrong with my approach? I would appreciate if someone would point me to a mathematical solution for the same.

+6
python math algorithm
source share
5 answers

If you provided comments, you would have noticed that the site owners or problem developer is a moron.

He had in mind to say “from 0 to 10000,” and not “from 1 to 10000,” but apparently the problem cannot be edited, or the attendant does not want to do this.

The amount is disabled by 1, since 1<<0 is 1, which adds 1 to the amount.

Try sending 67783432.

Note I understand that a call to site owners or their attendant may seem harsh, but accuracy is very important when posting content on the Math site. Having such a site without the ability or requirement to fix the wrong problems seems to me stupid.

+9
source share

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 

(Note that this calculates the sum of P (i) for i = 0 to 10,000.)

+3
source share

Your solution takes quite a long time to run (more than a minute, anyway). Is there a time limit imposed by the judge on the time that may be required to resolve?

Also, if you use Python 3, then the split operator ( /= ) always produces a floating point result. In Python 2, the result will be truncated by 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 
0
source share

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 remembers:

 >> 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 
0
source share

Actually, since Java cannot create such large numbers (unless you use the BigInteger class - which I have never used), it is better if you use flexible languages ​​such as Python

Python gave me 2 ** 1000. its a very large 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 the sum of each digit

0
source share

All Articles