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;
//	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值