日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

power(乘幂)函数剖析

發(fā)布時(shí)間:2024/4/17 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 power(乘幂)函数剖析 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

近來學(xué)習(xí)STL,看到power函數(shù)的實(shí)現(xiàn)感覺挺有趣,記錄一下。

1. 一般情況下,我自己要實(shí)現(xiàn)乘冪函數(shù)會(huì)這樣實(shí)現(xiàn):

int power(int x,size_t n) {int result = 1;while (n--)result *= x;return result; }

這樣即使實(shí)現(xiàn),這里的時(shí)間復(fù)雜度和n有關(guān),時(shí)間復(fù)雜度為0(n)。

2. 看了stl源碼實(shí)現(xiàn)是這樣:

// Returns __x ** __n, where __n >= 0. _Note that "multiplication" // is required to be associative, but not necessarily commutative. //意思是multiplication要滿足結(jié)合律,但不需要滿足交換律 template <class _Tp, class _Integer, class _MonoidOperation> _Tp __power(_Tp __x, _Integer __n, _MonoidOperation __opr) //這里第三個(gè)參數(shù)是一個(gè)二元操作函數(shù) {if (__n == 0)return identity_element(__opr); //返回1else {while ((__n & 1) == 0) //如果n為偶數(shù) {__n >>= 1;__x = __opr(__x, __x);}_Tp __result = __x;__n >>= 1;while (__n != 0) {__x = __opr(__x, __x);if ((__n & 1) != 0) //如果n為奇數(shù)__result = __opr(__result, __x);__n >>= 1;}return __result;} }template <class _Tp, class _Integer> inline _Tp __power(_Tp __x, _Integer __n) {return __power(__x, __n, multiplies<_Tp>()); }// Alias for the internal name __power. Note that power is an extension, // not part of the C++ standard. template <class _Tp, class _Integer, class _MonoidOperation> inline _Tp power(_Tp __x, _Integer __n, _MonoidOperation __opr) //也可以自定義,傳進(jìn)去一個(gè)函數(shù) {return __power(__x, __n, __opr); }template <class _Tp, class _Integer> inline _Tp power(_Tp __x, _Integer __n) //默認(rèn)情況下是乘冪 {return __power(__x, __n); }

這里:當(dāng)n為偶數(shù)時(shí),X^n=(X^2)^(2/n),此時(shí)看2/n是否還是偶數(shù),如果是則繼續(xù),否則,轉(zhuǎn)向n是奇數(shù)的情況;

? ? ? ? ? ?當(dāng)n為奇數(shù)時(shí),X^n=X*X^(n-1);

例如計(jì)算5^6=(5^2)^3,也就是計(jì)算25^3。

這種情況和第三種情況類似,只是當(dāng)n開始為偶數(shù)時(shí),比第三種方法的效率更高,n為奇數(shù)時(shí),和第三種方法時(shí)間復(fù)雜度一樣。

3. 第三種實(shí)現(xiàn),和stl源碼差不多,只是表示更簡潔,和第二種情況相比效率會(huì)差點(diǎn):

int power(int x, size_t n) {if(n == 0)return 1;int result = 1;while(n){if(n & 1) //n為奇數(shù)時(shí)result *= x; n >>= 1;x *= x; }
return result; }

如計(jì)算5^6是6化為二進(jìn)制為0110,所以這里5^6=5^2*5^4,這里時(shí)間復(fù)雜度為0((log2n)+1)

轉(zhuǎn)載于:https://www.cnblogs.com/liuamin/p/7107202.html

總結(jié)

以上是生活随笔為你收集整理的power(乘幂)函数剖析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。