算法是比较低效的.仅仅是为了练习Python.
#-*- coding:gb2312 -*- """北大ACM 1001 exponentiation 基本思路: 1.3099*12 去掉小数点后倒序得到[9,9,0,3,1] [9,9,3,0,1] * [9,9,0,3,1] = [9,9,0,3,1]*9*10^0 = [81, 81, 0,27, 9] + [9,9,0,3,1]*9*10^1 + [810, 810, 0,270, 90] + [9,9,0,3,1]*0*10^2 + [0, 0, 0,0, 0] + [9,9,0,3,1]*3*10^3 + [27000,27000,0,9000, 3000] + [9,9,0,3,1]*1*10^4 + [90000,90000,0,30000,10000] = [117891,117891,0,39297,13099] = [1,129680(117891+11789),0,39297,13099] = [1,0,12968,39297,13099] = ... = [1,0,8,3,17158] = [1,0,8,3,8,1715] = ... = [1,0,8,3,8,5,1,7,1] 然后倒序即可 小数点位置计算方法: 1.3099**2 = 1.71583801,小数位数为4*2 0.999**2 = 0.998001,小数位数为3*2 可以推出n,n有m位小数,则n**k的结果有m*k位小数 需要注意的是补齐前面的0,例如0.018**2 = 0.000324,需要在前面补齐0,使总位数为3*2=6 """ def foo(f, n): '''0.0 < f < 99.999, 0 < n <= 25 最终print结果,0.00123输出为.00123''' s = str(f) '''计算小数点位置''' dotPos = s.find(".") if dotPos != -1: dotPos = len(s)-1 - dotPos orgList = [int(e) for e in s if e != "."] orgList.reverse() sumList = orgList[::] for z in range(n-1): tmpList = sumList[::] for i in range(0, len(orgList)): if orgList[i] == 0: continue for j in range(0, len(sumList)): if i == 0: sumList[j] = tmpList[j]*orgList[i]*(10**i) else: sumList[j] += tmpList[j]*orgList[i]*(10**i) '''进位计算''' comlist(sumList) if f < 1: for e in range(dotPos*n-len(sumList)): sumList.append(0) sumList.reverse() sumList.insert(len(sumList) - dotPos*n, ".") s = "" for e in sumList: s += str(e) print(s) def comlist(l, n=0): '''进位计算,当有多位需要进位时,递归调用本函数并可指定开始进位的位数''' for i in range(n, len(l)): if l[i] > 9: t = int(l[i]/10) if i == len(l)-1: '''需要新增加元素''' l.append(t) l[i] = l[i]%10 '''新增加的元素可能会大于9,需要进一步进位''' comlist(l, i+1) else: l[i] = l[i]%10 l[i+1] += t if __name__ == "__main__": foo(5.1234, 15)