首页 > 代码库 > UVA10518 - How Many Calls?(矩阵快速幂)
UVA10518 - How Many Calls?(矩阵快速幂)
题目链接
题意:求第n个斐波那契数的递归次数MOD b
思路:用矩阵快速幂求斐波那契数列,然后打表找出递归次数的规律为f(n) = 2 * F(n) - 1(F(n)为斐波那契数)。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> typedef long long ll; using namespace std; ll n, b; struct mat{ ll s[2][2]; mat(ll a = 0, ll b = 0, ll c = 0, ll d = 0) { s[0][0] = a; s[0][1] = b; s[1][0] = c; s[1][1] = d; } }c(1, 1, 1, 0), tmp(1, 0, 0, 1); mat operator * (const mat& p, const mat& q) { mat state; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) state.s[i][j] = (p.s[i][0] * q.s[0][j] + p.s[i][1] * q.s[1][j]) % b; return state; } mat pow_mod(ll k) { if (k == 0) return tmp; else if (k == 1) return c; mat a = pow_mod(k / 2); a = a * a; if (k % 2) a = a * c; return a; } int main() { int t = 1; while (scanf("%lld %lld", &n, &b) && (n || b)) { mat temp = pow_mod(n); ll ans = temp.s[0][0]; printf("Case %d: %lld %lld %lld\n", t++, n, b, (2 * ans - 1 + b) % b); } return 0; }
UVA10518 - How Many Calls?(矩阵快速幂)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。