M斐波那契数列 hdu 4549

来源:互联网 发布:动漫网络黑名单 编辑:程序博客网 时间:2024/06/07 00:53

M斐波那契数列

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 520    Accepted Submission(s): 146


Problem Description
M斐波那契数列F[n]是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F[n]的值吗?
 


 

Input
输入包含多组测试数据;
每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )
 


 

Output
对每组测试数据请输出一个整数F[n],由于F[n]可能很大,你只需输出F[n]对1000000007取模后的值即可,每组数据输出一行。
 


 

Sample Input
0 1 06 10 2
 


 

Sample Output
060
 

 

package hpu;import java.util.Scanner;public class HDU4579_3 {public static int a, b, n;public static long mod = 1000000007;public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNextInt()) {a = sc.nextInt();b = sc.nextInt();n = sc.nextInt();if(n == 0) {System.out.println(a);}else if(n == 1) {System.out.println(b);} else {sovle();}}}private static void sovle() {long[][] result = {{1, 0}, {0, 1}};long[][] f = {{1, 1},{1, 0}};while(n > 0) {if((n&1) == 1) {matrixMul(result, f);}matrixMul(f, f);n >>= 1;}long bn = result[0][1];long an = result[1][1];long bbn = powMod(b, bn, mod);long aan = powMod(a, an, mod);long r = bbn*aan%mod;System.out.println(r);}//矩阵相乘private static void matrixMul(long[][] a, long[][] b) {long c[][] = new long[2][2];for(int i=0; i<2; i++) {for(int j=0; j<2; j++) {for(int k=0; k<2; k++) {c[i][j] = (c[i][j]+a[i][k]*b[k][j])%(mod-1);//%(mod-1)的原因:费马小定理(a^(m-1) = 1%m)(m==素数))}}}for(int i=0; i<2; i++) {for(int j=0; j<2; j++) {a[i][j] = c[i][j];}}}//求a^n%mprivate static long powMod(long a, long n, long m) {long c = 1;while(n > 0) {if((n&1) == 1) {c = c*a%m;}a = a*a%m;n >>= 1;}return c;}//求a^n%m(递归型)//private static long powMod(long a, long n, long m) {//if(n==0) return 1;//long x = powMod(a, n/2, m);//long ans = (long)x*x%m;//if(n%2 == 1) ans = ans*a%m;//return ans;//}}