poj-3070 Fibonacci(矩阵快速幂 + 斐波那契数列)

来源:互联网 发布:淘宝卖家加分规则 编辑:程序博客网 时间:2024/06/06 01:01

原题链接

Fibonacci
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 13219 Accepted: 9394

Description

In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

An alternative formula for the Fibonacci sequence is

.

Given an integer n, your goal is to compute the last 4 digits of Fn.

Input

The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

Output

For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

Sample Input

099999999991000000000-1

Sample Output

0346266875



#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>#include <vector>#include <map>#include <cmath>#include <queue>#define maxn 1000005#define MOD 10000using namespace std;typedef long long ll;int p1[2][2], p2[2][2], p3[2][2];void Multi(int (*k1)[2], int (*k2)[2], int (*k3)[2]){for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++){k3[i][j] = k1[i][0] * k2[0][j] + k1[i][1] * k2[1][j];k3[i][j] %= MOD;}}void solve(int n){while(n){if(n&1){     Multi(p1, p2, p3); memcpy(p2, p3, sizeof(p3));}Multi(p1, p1, p3);memcpy(p1, p3, sizeof(p3));n >>= 1;}}int main(){//freopen("in.txt", "r", stdin);int n;while(scanf("%d", &n) == 1 && n != -1){if(n == 0)  puts("0");else if(n == 1) puts("1");else{p2[0][0] = 1, p2[0][1] = 0;p2[1][0] = 0, p2[1][1] = 1;p1[0][0] = 1, p1[0][1] = 1;p1[1][0] = 1, p1[1][1] = 0;solve(n-1);printf("%d\n", p2[0][0]);}}return 0;}


0 0
原创粉丝点击