poj 3070 java实现矩阵快速幂



链接:戳这里


代码:

import java.util.Scanner;

public class Poj3070 {
	static Scanner cin = new Scanner(System.in);
	static long mod=10000;
	static public class Matrix{
		public long[][] ma = new long[2][2];
		public Matrix(){
			for(int i=0;i<2;i++){
				for(int j=0;j<2;j++){
					ma[i][j]=0;
				}
			}
		}
	}
	static public Matrix Mult(Matrix a,Matrix b){
		Matrix c = new Matrix();
	    for(int i=0;i<2;i++){
	        for(int j=0;j<2;j++){
	            for(int k=0;k<2;k++){
	                c.ma[i][j]=(c.ma[i][j]+a.ma[i][k]*b.ma[k][j]%mod)%mod;
	            }
	        }
	    }
	    return c;
	}
	static public Matrix Mpow(Matrix a,long N){
		Matrix tmp = new Matrix();
		for(int i=0;i<2;i++) tmp.ma[i][i]=1;
		while(N!=0){
			if(N%2==1) tmp=Mult(tmp,a);
			a=Mult(a,a);
			N/=2;
		}
		return tmp;
	}
	public static void main(String[] args) {
		while(true){
			long N = cin.nextLong();
			if(N==-1) break;
			if(N==0){
				System.out.println("0");
				continue;
			}
			Matrix a = new Matrix();
			Matrix b = new Matrix();
			a.ma[0][0]=1;
			a.ma[0][1]=1;
			a.ma[1][0]=1;
			b=Mpow(a,N);
			System.out.println(b.ma[1][0]%mod);
		}
	}
}


你可能感兴趣的:(poj 3070 java实现矩阵快速幂)