求a+ aa + aaa + aaaa +⋯+ a ... aa, 最后一项有n个a, 例如2+22+222+2222, 15+1515+151515+15151515
我在CSDN看了不少的求和,发现用的最多的就是:
def funny_function(a, n):
t = a
m = a
for i in range(n-1):
t = 10*t + a
m += t
return m
funny_function(2,4)
如果a是两位数,如a = 12,或者三位数甚至更多位数, 则结果不对。下面是我的代码 (python 3):
代码1: casting
def element(x, n):
return int(str(x) * n)
def funny_function(a, n):
s=0
for i in range(1, n + 1):
s += element(a, i)
return (s)
代码2:类似在csdn看到的方法,不过考虑到多位数
# get digit(s) of the original input, ten digit, hundred digit...
def get_digits(x):
ds = []
while x > 0:
x, d = divmod(x, 10)
ds.append(d)
ds.reverse()
return ds
# get element of each item
def element(x, n):
ds = get_digits(x)
res = 0
for i in range(n):
for d in ds:
res = 10 * res + d
return res
def funny_function(a, n):
res = a
for i in range(2, n + 1):
res += element(a, i)
return res