UVA 10518 How Many Calls?

Problem J
How Many Calls?
Input: 
standard input
Output: 
standard output

Time Limit: 5 seconds

The fibonacci number is defined by the following recurrence:

  • fib(0) = 0
  • fib(1) = 1
  • fib(n) = fib(n-1)+fib(n-2)

But we're not interested in the fibonacci numbers here. We would like to know how many calls does it take to evaluate the n th fibonacci number if we follow the given recurrence. Since the numbers are going to be quite large, we'd like to make the job a bit easy for you. We'd only need the last digit of the number of calls, when this number is represented in base b.

Input

Input consists of several test cases. For each test you'd be given two integers n (0 <= n < 263-1), b (0 < b <= 10000). Input is terminated by a test case where n=0 and b=0, you must not process this test case.

Output

For each test case, print the test case number first. Then print nb and the last digit (in base b) of the number of calls. There would be a single space in between the two numbers of a line. Note that the last digit has to be represented in decimal number system.

Sample Input

0 100
1 100
2 100
3 100
10 10
0 0

Sample Output

Case 1: 0 100 1
Case 2: 1 100 1
Case 3: 2 100 3
Case 4: 3 100 5
Case 5: 10 10 7


#include <cstdio>
#include <cstring>

const int N = 3;
typedef long long LL;
LL MOD;

struct Matrix{
	LL ary[N][N];
	void init() {
		memset(ary, 0, sizeof(ary));
	}
	Matrix() {
		init();
	}
};

const Matrix operator*(const Matrix & A, const Matrix & B) {
	Matrix t;
	for (int i = 0; i < N; ++i)
		for (int j = 0; j < N; ++j) {
			for (int k = 0; k < N; ++k) 
				t.ary[i][j] += A.ary[i][k] * B.ary[k][j];
			t.ary[i][j] = t.ary[i][j] % MOD;
		}
	return t;
}

LL quick_pow(LL n) {
	if (n <= 1) return 1 % MOD;
	Matrix ans, tmp;
	ans.ary[0][0] = 3 % MOD;;
	ans.ary[0][1] = ans.ary[0][2] = ans.ary[1][0] = ans.ary[1][2] = ans.ary[1][1] = 1 % MOD;

	tmp.ary[0][0] = tmp.ary[1][0] = tmp.ary[0][1] = tmp.ary[2][0] = tmp.ary[2][2] = 1;

	n -= 2;
	while (n) {
		if (n & 1)
			ans = ans * tmp;
		n >>= 1;
		tmp = tmp * tmp;
	}

	return ans.ary[0][0];
}

int main() {
	int cnt = 0;
	LL n;

	while (~scanf("%lld%lld", &n, &MOD), n + MOD > 0) {
		LL ans;

		ans = quick_pow(n);

		printf("Case %d: %lld %lld %lld\n", ++cnt, n, MOD, ans);
	}

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值