列表

详情


NC51048. Fibonacci

描述

In the Fibonacci integer sequence, , and for . 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.

输入描述

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.

输出描述

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).

示例1

输入:

0
9
999999999
1000000000
-1

输出:

0
34
626
6875

说明:

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:

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 4ms, 内存消耗: 364K, 提交时间: 2020-06-02 10:33:09

#include<bits/stdc++.h>
using namespace std;
const int p=10000;
int n;
void mul(int f[2],int a[2][2]) {
	int c[2]= {};
//	memset(c,0,sizeof(c));
	for(int i=0; i<2; i++)
		for(int j=0; j<2; j++) {
			c[i]=(c[i]+(long long)f[j]*a[j][i])%p;
		}
	memcpy(f,c,sizeof(c));
}
void mulself(int a[2][2]) {
	int c[2][2]= {};
//	memset(c,0,sizeof(c));
	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]+(long long)a[i][k]*a[k][j])%p;
	memcpy(a,c,sizeof(c));
}
int main() {
	while(cin>>n&&n!=-1) {
		int f[2]= {0,1},a[2][2]= {0,1,1,1};
		for(; n; n>>=1) {
			if(n&1)mul(f,a);
			mulself(a);
		}
		cout<<f[0]<<endl;
	}
	return 0;
}

C++ 解法, 执行用时: 38ms, 内存消耗: 792K, 提交时间: 2021-12-31 17:23:36

#include<bits/stdc++.h>
using namespace std;
int a[100001],n;
int pv(int n){
	a[0]=0;
	a[1]=1;
	for(int i=2;i<100001;i++)a[i]=(a[i-1]+a[i-2])%10000;
	return a[n%15000]%10000;
} 
int main(){
	while(cin>>n&&n!=-1)cout<<pv(n)<<"\n";
	return 0;
}

上一题