zoukankan      html  css  js  c++  java
  • 算法:求幂(python版)

    分别用迭代方法和递归方法实现求幂
    迭代方法的时间复杂度为O(n),空间复杂度为O(1)
    递归方法1的时间复杂度为O(logn),空间复杂度为O(logn)
    递归方法2的时间复杂度为O(n),空间复杂度为O(n)

    #
    !/usr/bin/env python #coding -*- utf:8 -*- def pow_1(x, n, choice): if choice==0: return pow_1_iter(x, n, 1) if choice==1: return pow_1_rec(x, n) #iteration def pow_1_iter(x, counter, product): if counter==0: return product else: return pow_1_iter(x, counter-1, x*product) #recursion1 def pow_1_rec(x, counter): if counter==0: return 1 #偶数情况 if(even(counter)): return pow_1_rec(x*x, counter//2) #奇数情况 else: return x * pow_1_rec(x, counter-1) #return x * pow_1_rec(x*x, counter//2) '''
    #recursion2
    def pow_2_rec(x, counter):
    if n==0:
    return 1
    else:
    return x*pow_2_rec(x,counter-1)

    ''' #判断counter是否为偶数 def even(i): if i%2==0: return True else: return False if __name__=='__main__': a = int(input("Please enter the x:")) b = int(input("Please enter the m:")) c = int(input("Which method do you want?(0:iteration, 1:recursion) ")) print("result: ",pow_1(a, b, c))
  • 相关阅读:
    A. Ivan the Fool and the Probability Theory
    C2. Good Numbers (hard version)
    C. p-binary
    H. Happy Birthday
    idea使用goeasy实现webSocket
    idea新建一个maven项目
    FreeMaker入门介绍
    mui预加载
    mui底部选项卡切换实现
    BootStrap 学习笔记一
  • 原文地址:https://www.cnblogs.com/xautxuqiang/p/6059613.html
Copyright © 2011-2022 走看看