演算法是比較低效的.僅僅是為了練習Python.
#-*- coding:gb2312 -*-<br />"""北大ACM 1001 exponentiation</p><p>基本思路:<br /> 1.3099*12<br /> 去掉小數點後倒序得到[9,9,0,3,1]<br /> [9,9,3,0,1] * [9,9,0,3,1] = [9,9,0,3,1]*9*10^0 = [81, 81, 0,27, 9]<br /> + [9,9,0,3,1]*9*10^1 + [810, 810, 0,270, 90]<br /> + [9,9,0,3,1]*0*10^2 + [0, 0, 0,0, 0]<br /> + [9,9,0,3,1]*3*10^3 + [27000,27000,0,9000, 3000]<br /> + [9,9,0,3,1]*1*10^4 + [90000,90000,0,30000,10000]<br /> = [117891,117891,0,39297,13099]<br /> = [1,129680(117891+11789),0,39297,13099]<br /> = [1,0,12968,39297,13099]<br /> = ...<br /> = [1,0,8,3,17158]<br /> = [1,0,8,3,8,1715]<br /> = ...<br /> = [1,0,8,3,8,5,1,7,1]<br /> 然後倒序即可<br /> 小數點位置計算方法:<br /> 1.3099**2 = 1.71583801,小數位元為4*2<br /> 0.999**2 = 0.998001,小數位元為3*2<br /> 可以推出n,n有m位小數,則n**k的結果有m*k位小數<br /> 需要注意的是補齊前面的0,例如0.018**2 = 0.000324,需要在前面補齊0,使總位元為3*2=6<br />"""</p><p>def foo(f, n):<br /> '''0.0 < f < 99.999, 0 < n <= 25<br /> 最終print結果,0.00123輸出為.00123'''<br /> s = str(f)<br /> '''計算小數點位置'''<br /> dotPos = s.find(".")<br /> if dotPos != -1:<br /> dotPos = len(s)-1 - dotPos<br /> orgList = [int(e) for e in s if e != "."]<br /> orgList.reverse()<br /> sumList = orgList[::]</p><p> for z in range(n-1):<br /> tmpList = sumList[::]<br /> for i in range(0, len(orgList)):<br /> if orgList[i] == 0:<br /> continue<br /> for j in range(0, len(sumList)):<br /> if i == 0:<br /> sumList[j] = tmpList[j]*orgList[i]*(10**i)<br /> else:<br /> sumList[j] += tmpList[j]*orgList[i]*(10**i)<br /> '''進位計算'''<br /> comlist(sumList)<br /> if f < 1:<br /> for e in range(dotPos*n-len(sumList)):<br /> sumList.append(0)<br /> sumList.reverse()</p><p> sumList.insert(len(sumList) - dotPos*n, ".")<br /> s = ""<br /> for e in sumList:<br /> s += str(e)<br /> print(s)</p><p>def comlist(l, n=0):<br /> '''進位計算,當有多位需要進位時,遞迴調用本函數並可指定開始進位的位元'''<br /> for i in range(n, len(l)):<br /> if l[i] > 9:<br /> t = int(l[i]/10)<br /> if i == len(l)-1:<br /> '''需要新增加元素'''<br /> l.append(t)<br /> l[i] = l[i]%10<br /> '''新增加的元素可能會大於9,需要進一步進位'''<br /> comlist(l, i+1)<br /> else:<br /> l[i] = l[i]%10<br /> l[i+1] += t</p><p>if __name__ == "__main__":<br /> foo(5.1234, 15)