python實現pow函式(求n次冪,求n次方)

2022-08-24 22:06:14 字數 2674 閱讀 4282

目錄實現 pow(x, n),即計算 x 的 n 次冪函式。其中n為整數。pow函式的實現——leetcode

解法1:暴力法

不是常規意義上的暴力,過程中通過動態調整底數的大小來加快求解。**如下:

class solution:

def mypow(self, x: float, n: int) -> float:

judge = true

if n<0:

n = -n

judge = false

if n==0:

return 1

final = 1 # 記錄當前的乘積值

tmp = x # 記錄當前的因子

count = 1 # 記錄當前的因子是底數的多少倍

while n>0:

if n>=count:

final *= tmp

tmp = tmp*x

n -= count

count +=1

else:

tmp /= x

count -= 1

return final if judge else 1/final

解法2:根據奇偶冪分類(遞迴法,迭代法,位運演算法)

如果n為偶數,則pow(x,n) = pow(x^2, n/2);

如果n為奇數,則pow(x,n) = x*pow(x, n-1)。

遞迴**實現如下:

class solution:

def mypow(self, x: float, n: int) -> float:

if n<0:

n = -n

return 1/self.help_(x,n)

return self.help_(x,n)

def help_(self,x,n):

if n==0:

return 1

if n%2 == 0: #如果是偶數

return self.help_(x*x, n//2)

# 如果是奇數

return self.help_(x*x,(n-1)//2)*x

迭代**如下:

class solution:

def mypow(self, x: float, n: int) -> float:

judge = true

if n < 0:

n = -n

judge = false

final = 1

while n>0:

if n%2 == 0:

x *=x

n //= 2

final *= x

n -= 1

return final if judge else 1/final

python位運算子簡介

其實跟上面的方法類似,只是通過位運算子判斷奇偶性並且進行除以2的操作(移位操作)。**如下:

class solution:

def mypow(self, x: float, n: int) -> float:

judge = true

if n < 0:

n = -n

judge = false

final = 1

while n>0:

if n & 1: #代表是奇數

final *= x

x *= x

n >>= 1 # 右移一位

return final if judge else 1/final

實現 pow(x, n),即計算 x 的 n 次冪函式。其中x大於0,n為大於1整數

解法:二分法求開方

思路就是逐步逼近目標值。以x大於1為例:

設定結果範圍為[low, high],其中low=0, high = x,且假定結果為r=(low+high)/2;

如果r的n次方大於x,則說明r取大了,重新定義low不變,high= r,r=(low+high)/2;

如果r的n次方小於x,則說明r取小了,重新定義low=r,high不變,r=(low+high)/2;

**如下:

class solution:

def mypow(self, x: float, n: int) -> float:

# x為大於0的數,因為負數無法開平方(不考慮複數情況)

if x>1:

low,high = 0,x

else:

low,high =x,1

while true:

r = (low+high)/2

judge = 1

for i in range(n):

judge *= r

if x >1 and judge>x:break # 對於大於1的數,如果當前值已經大於它本身,則無需再算下去

if x <1 and judgex:

high = r

else:

low = r

pow 函式自實現

題目 實現函式double power double base,int exponent 求base的exponent次方。不得使用庫函式同時不需要考慮大數問題。其實這道題就是要實現pow這個庫函式。你可不要自以為這道題目簡單,直接給出乙個for迴圈了事。像下面這樣 double power dou...

python函式求n年後本息 python函式作業

標籤 1.寫函式,接收n個數字,求這些數字的和 函式名不定義為sum,避免與內建函式衝突 def sum func args total 0 for i in args total i return total print sum func 1,3,4,33,44,66 2.中列印出來的a,b,c分...

STL中對Pow函式的實現

在 stl原始碼剖析 中看到了pow函式在stl中的實現,感覺程式寫的非常巧妙。列出原始碼 template inline t identity element plus template inline t identity element multiplies template inline t ...