算法导论-3 divide-and-conquer-strassen-fibonacci-polynomial-multiplication

1、计算 x(实数) 的 n(整数) 次方 ,O(logn)

codes:

import java.util.Scanner; public class Power { public static double power(double x, int n){ if(n==0) return 1; if(n%2==0){ // even double temp= power(x,n/2); return temp*temp; } else{ // odd double temp=power(x,(n-1)/2); return temp*temp*x; } } public static void main(String[] args) { Scanner in=new Scanner(System.in); while(true) { double x=in.nextDouble(); int n=in.nextInt(); System.out.println(power(x,n)); System.out.println(Math.pow(x, n)); } } }

 

2、求Fibonacci数,O(logN),矩阵相乘

codes:

import java.util.Scanner; //矩阵 class Matrix{ //初始为基本矩阵 public int [][] elem={{1,1},{1,0}}; //矩阵相乘,修改本身 public Matrix multiply(Matrix m2){ int temp[][]=new int[2][2]; temp[0][0]=elem[0][0]*m2.elem[0][0]+elem[0][1]*m2.elem[1][0]; temp[0][1]=elem[0][0]*m2.elem[0][1]+elem[0][1]*m2.elem[1][1]; temp[1][0]=elem[1][0]*m2.elem[0][0]+elem[1][1]*m2.elem[0][1]; temp[1][1]=elem[1][0]*m2.elem[0][1]+elem[1][1]*m2.elem[1][1]; for(int i=0;i<2;i++) for(int j=0;j<2;j++) elem[i][j]=temp[i][j]; return this; } public String toString(){ return elem[0][0]+" "+elem[0][1]+"/n"+elem[1][0]+" "+elem[1][1]; } } public class Fibo { //通过矩阵相乘求Fibo O(logN) public static int LogNFibo(int n){ if(n==0) return 0; Matrix m=power(n); return m.elem[0][1]; } public static final Matrix base=new Matrix(); public static Matrix power(int n){ if(n==1){ return new Matrix(); } if(n%2==0){ // even Matrix temp=power(n/2); return temp.multiply(temp); } else{ // odd Matrix temp=power((n-1)/2); return temp.multiply(temp).multiply(base); } } //自底向上法 O(n) public static int LinearFibo(int n){ int []ans=new int[n+1]; ans[0]=0; ans[1]=1; for(int i=2;i<=n;i++){ ans[i]=ans[i-1]+ans[i-2]; } return ans[n]; } public static void main(String[] args) { Scanner in=new Scanner(System.in); while(in.hasNext()){ int n=in.nextInt(); System.out.println(LinearFibo(n)); System.out.println(LogNFibo(n)); } } }

你可能感兴趣的:(算法导论-3 divide-and-conquer-strassen-fibonacci-polynomial-multiplication)