矩陣快速冪&求大斐波那契&poj3070(java)
阿新 • • 發佈:2018-12-22
題目連結
核心思想為:
從右往左。可以一直遞推,然後到最後一項,然後快速冪求矩陣,矩陣最終的結果就是所求結果。
import java.util.Scanner;
public class testF {
public static void main(String[] args) {
// TODO 自動生成的方法存根
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
int n=sc.nextInt();
if(n==-1)break;
if(n==0) {System.out.println(0) ;}
else {
n-=2;//
int a[][]= {{1,1},{1,0}};
int b[][]={{1,1},{1,0}};
int time=0;
while(n>0)
{
if(n%2==1)
{
b=q(a, b);
}
a=q(a, a);n/=2;
}
System.out.println((b[0][0]));
}
}
}
static int [][] q(int a[][],int b[][]){//
int value1=a[0][0]*b[0][0]%10000+a[0][1]*b[ 1][0]%10000;//左上
int value2=a[0][0]*b[0][1]%10000+a[0][1]*b[1][1]%10000;//左上
int value3=a[1][0]*b[0][0]%10000+a[1][1]*b[1][0]%10000;//左上
int value4=a[1][0]*b[0][1]%10000+a[1][1]*b[1][1]%10000;//左上
int c[][]=new int [2][2];
c[0][0]=value1%10000;
c[0][1]=value2%10000;
c[1][0]=value3%10000;
c[1][1]=value4%10000;
return c;
}
}