1. 程式人生 > >M斐波那契數列 hdu 4549

M斐波那契數列 hdu 4549

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 0 6 10 2 Sample Output 0 60
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%m
	private 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;
//	}

}