# -*- coding: utf-8 -*-
'''
Python程序员面试算法宝典---解题总结: 第6章 基本数字运算 6.12 如何计算一个数的n次方
题目:
给定一个数d和n,如何计算d的n次方?例如: d=2, n=3, d的n次方为8。
分析:
这个是之前见过的题目。
关键就是用递归。
每次计算d的n/2次方。
需要考虑的是n为奇数的情况。
关键:
1 在递归计算的过程中考虑如果n为奇数,就需要最后乘以数字本身
参考:
Python程序员面试算法宝典
'''
def _powerOfN(d, n, resultDict):
# 如果之前已经搜索过,就直接返回
if resultDict.get(n, None) != None:
return resultDict.get(n)
# 否则,开始递归计算,递归基是n = 1的时候,直接返回本身
if 1 == n:
resultDict[n] = d
return resultDict[n]
# 递归步
half = _powerOfN(d, n/2, resultDict)
result = half * half
# 注意,如果n为奇数,需要乘以本身
if n & 1 == 1:
result *= d
resultDict[n] = result
return resultDict[n]
def powerOfN(d, n):
# 为了保存之前的计算结果,这里用一个字典做记忆化搜索
resultDict = dict()
result = _powerOfN(d, n, resultDict)
return result
def process():
d = 2
n = 5
result = powerOfN(d, n)
print result
n = 6
result = powerOfN(d, n)
print result
n = 7
result = powerOfN(d, n)
print result
if __name__ == "__main__":
process()