快速幂(Fast_Power)
生活随笔
收集整理的這篇文章主要介紹了
快速幂(Fast_Power)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、定義
快速冪顧名思義,就是快速算某個數的多少次冪。
其時間復雜度為 O(log2N), 與樸素的O(N)相比效率有了極大的提高。
以下以求a的b次方來介紹
二、原理
把b轉換成2進制數
該2進制數第i位的權為(2^(i-1))
例如
a^11=a^(2^0+2^1+2^3)
11的二進制是1 0 1 1
11 = 2^3*1 + 2^2*0 + 2^1*1 + 2^0*1
因此,我們將a^11轉化為算a^(2^0)*a^(2^1)*a^(2^3)
int Fast_Power(int a, int b){int ans = 1;while(b>0){if(b % 2 == 1)ans *= a;b >>= 1;a *= a;}return ans; }由于指數函數是爆炸增長的函數,所以很有可能會爆掉int的范圍,一般題目會要求mod某個數c;
int PowerMod(int a, int b, int c){int ans = 1;a = a % c;while(b>0){if(b % 2 == 1)ans = (ans * a) % c;b >>= 1;a = (a * a) % c;}return ans; }JAVA版本一
private static int Fast_Power(int a, int b) {int s = 1;while (b > 0) {if (b % 2 == 1) {//b=b>>1保證了在最后一步肯定會執行該if判斷s = s * a;}a = a * a;b = b >> 1;}return s; }三、例題
?http://acm.hdu.edu.cn/showproblem.php?pid=1420(題解:https://blog.csdn.net/weixin_43272781/article/details/88952920)
http://acm.hdu.edu.cn/showproblem.php?pid=1061(題解:https://blog.csdn.net/weixin_43272781/article/details/88953103)
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的快速幂(Fast_Power)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 加分二叉树
- 下一篇: 质数(Prime_Number)