POJ - 3070 Fibonacci

来源:互联网 发布:手机淘宝能收藏店铺吗 编辑:程序博客网 时间:2024/06/17 14:32
Fibonacci
Time Limit: 1000MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u

Submit Status

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

Hint

As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

.

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

.

#include<iostream>       //斐波那契数列。N=10^9,一个可以选择的做法就是构造矩阵快速幂。由于模的是10000,所以也可以通过打表找循环节的方法做。#include<stdio.h>#include<cstdio>#include<cstring>#define ll long longusing namespace std;const int dim = 2;   //这三个数据可调整 int mod = 10000; int mk = 2;struct Matrix                                      //矩阵定义,相乘,求幂的模板{ll a[dim][dim];Matrix(){ memset(a, 0, sizeof(a)); }};Matrix operator *(const Matrix& a, const Matrix& b){Matrix ret;for (int i = 0; i<mk; ++i)for (int j = 0; j<mk; ++j)for (int k = 0; k<mk; ++k){ret.a[i][j] += a.a[i][k] * b.a[k][j];ret.a[i][j] %= mod;}return ret;}Matrix operator ^(Matrix x, ll n){Matrix ret;for (int i = 0; i<mk; ++i)ret.a[i][i] = 1;while (n){if (n & 1)ret = ret*x;x = x*x;n >>= 1;}return ret;}int main(){Matrix ap,fm;ap.a[0][0] = 1;            ap.a[0][1] = 1;ap.a[1][0] = 1;ap.a[1][1] = 0;long long int n;while (cin >> n&&n != -1){fm = ap^n;long long int ans = fm.a[0][1];cout << ans << endl;}}


0 0
原创粉丝点击