快速冪運算:
快速冪的目的就是做到快速求冪,假設我們要求a^b,按照樸素算法就是把a連乘b次,這樣一來時間複雜度是O(b)也即是O(n)級別,快速冪能做到O(logn),快了好多好多。它的原理如下:
假設我們要求a^b,那麼其實b是可以拆成二進制的,該二進制數第i位的權爲2^(i-1),例如當b==11時:
a11=a(2^0+2^1+2^3)
11的二進制是1011,11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1,因此,我們將a¹¹轉化爲算式 a2^0*a2^1*a2^3,也就是a1*a2*a8 ,看出來快的多了吧原來算11次,現在算三次,其中a1 a2 a8的計算方式代碼註釋裏面寫着。
代碼:
public class NExponent {
public static void main(String[] args) {
System.out.println(ex2(2, 3));
}
public static int ex(int a,int n){
if(n==0)return 1;
if(n==1)return a;
int temp = a; // a的1次方
int res = 1;
int exponent = 1;
while((exponent<<1)<n){
temp = temp * temp;
exponent = exponent << 1;
}
res *= ex(a,n-exponent);
return res * temp;
}
/**
* 快速冪 O(lgn)
*/
public static long ex2(long n,long m){
if(n==0) return 1;
long pingFangShu = n; // n 的 1 次方
long result = 1;
while (m != 0) {
// 遇1累乘現在的冪
if ((m & 1) == 1)
result *= pingFangShu;
// 每移位一次,冪累乘方一次
pingFangShu = pingFangShu * pingFangShu;
// 右移一位
m >>= 1;
}
return result;
}
}
題目:矩陣快速冪求解斐波那契數列
代碼:
public class Fib {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
System.out.print(fib(i)+" ");
}
}
// 矩陣運算求解斐波那契數列
static long fib(long n){
if (n == 1 || n == 2) return 1;
long[][] matrix = {
{ 0, 1 },
{ 1, 1 }
};
long[][] res = matrixPower(matrix, n - 1);// 乘方
res = matrixMultiply(new long[][] { { 1, 1 } }, res);// 矩陣相乘
return res[0][0];
}
public static long[][] matrixPower(long[][] matrix, long p) {
// 初始化結果爲單位矩陣,對角線爲1
long[][] result = new long[matrix.length][matrix[0].length];
// 單位矩陣,相當於整數的1
for (int i = 0; i < result.length; i++) {
result[i][i] = 1;
}
// 平方數
long[][] pingFang = matrix; // 一次方
while (p != 0) {
if ((p & 1) != 0) { // 當前二進制位最低位爲1,將當前平方數乘到結果中
result = matrixMultiply(result, pingFang);//
}
// 平方數繼續上翻
pingFang = matrixMultiply(pingFang, pingFang);
p >>= 1;
}
return result;
}
/**
* 矩陣乘法 矩陣1爲n*m矩陣,矩陣2爲m*p矩陣 結果爲n*p矩陣
*/
public static long[][] matrixMultiply(long[][] m1, long[][] m2) {
final int n = m1.length;
final int m = m1[0].length;
if (m != m2.length)
throw new IllegalArgumentException();
final int p = m2[0].length;
long[][] result = new long[n][p];// 新矩陣的行數爲m1的行數,列數爲m2的列數
for (int i = 0; i < n; i++) {// m1的每一行
for (int j = 0; j < p; j++) {// m2的每一列
for (int k = 0; k < m; k++) {
result[i][j] += m1[i][k] * m2[k][j];
}
}
}
return result;
}
}
結果: