Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing up digits !

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.

like image 850
Quixotic Avatar asked Feb 03 '11 19:02

Quixotic


2 Answers

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.

like image 187
Lasse V. Karlsen Avatar answered Oct 14 '22 04:10

Lasse V. Karlsen


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.)

like image 45
scoffey Avatar answered Oct 14 '22 04:10

scoffey