Skip to main content
Implementing a closed form solution
Source Link

Python (brute force solution)

f = lambda x: sum( sum( int(k) for k in str(i) ) for i in xrange(1, x+1) )

>>> f(12)
51
>>> f(5)
15

Python (a more elegant solution)

a = lambda x: all(i=='9' for i in x)
l = lambda x: int(x) if a(x) else 10**(len(x) -1 )- 1
s = lambda i: 45*(i*(10**(i-1)))
f = lambda k:s( len(k) - (0 if a(k) else 1 ) ) + f( str(int(k) - l( k )) ) if len( k ) > 1 else sum( xrange(1, int(k)+1) )

>>> f('12')
51
>>> f('5')
15

Python

f = lambda x: sum( sum( int(k) for k in str(i) ) for i in xrange(1, x+1) )

>>> f(12)
51
>>> f(5)
15

Python (brute force solution)

f = lambda x: sum( sum( int(k) for k in str(i) ) for i in xrange(1, x+1) )

>>> f(12)
51
>>> f(5)
15

Python (a more elegant solution)

a = lambda x: all(i=='9' for i in x)
l = lambda x: int(x) if a(x) else 10**(len(x) -1 )- 1
s = lambda i: 45*(i*(10**(i-1)))
f = lambda k:s( len(k) - (0 if a(k) else 1 ) ) + f( str(int(k) - l( k )) ) if len( k ) > 1 else sum( xrange(1, int(k)+1) )

>>> f('12')
51
>>> f('5')
15
deleted 3 characters in body
Source Link

Python

f = lambda x: sum( sum( map(int,(k) for k in str(i).split() ) ) for i in xrange(1, x+1) )

>>> f(12)
7851
>>> f(5)
15

Python

f = lambda x: sum( sum( map(int, str(i).split() ) ) for i in xrange(1, x+1) )

>>> f(12)
78
>>> f(5)
15

Python

f = lambda x: sum( sum( int(k) for k in str(i) ) for i in xrange(1, x+1) )

>>> f(12)
51
>>> f(5)
15
Source Link

Python

f = lambda x: sum( sum( map(int, str(i).split() ) ) for i in xrange(1, x+1) )

>>> f(12)
78
>>> f(5)
15