数值的整数次方

 

效率0(lgn)

 

这个求幂函数无论 基数 或 次方 为 正数或者为负数都是成立的.只是他们都为整数罢了。

 

注意了哦,这个代码必须要用python3才能运行正确,因为python3的 整数除以整数 可以得到 小数。 1/2 = 0.5。 python2 1/2 = 0.

 1 #!/usr/bin/env python3
 2 
 3 def pow1(base, exponent):
 4         if exponent == 0:       return 1
 5         if exponent == -1:      return (1/base)
 6         if exponent & 1 == 1:
 7                 return base * pow1(base, exponent-1)
 8         else:
 9                 return pow1(base * base, exponent >> 1)
10 
11 if __name__ == "__main__":
12         print(pow1(-2,-5))


-5 // 2= -3

-3 // 2 = -1

-1 // 2 = -1

所以当exponent为 -1 时,返回 1/base.

相关文章:

  • 2021-08-28
  • 2022-12-23
  • 2022-01-19
  • 2021-06-04
  • 2022-12-23
  • 2022-01-30
  • 2021-11-15
猜你喜欢
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2022-02-14
  • 2022-12-23
  • 2022-01-29
  • 2021-07-12
相关资源
相似解决方案