Fibonacci

来源:互联网 发布:php 自己开发mvc框架 编辑:程序博客网 时间:2024/05/28 05:18

问题 C: Fibonacci

题目描述

In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn Fn − 1 Fn − 2 for n ≥ 2. For example, the first ten termsof 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 testcase consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file isdenoted 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).

样例输入

0

9

999999999

1000000000

-1

样例输出

0

34

626

6875

 

这一题搬来应该用矩阵快速幂求Fibonacci数列的。但是原谅我很笨,用C语言我写不出来,还是算法我没有搞清楚,希望有大神能够帮忙教懂我算法。

我呢,采取了一个投机取巧的方法,找到了规律。在OJ上ac了哦!

代码如下:

#include<stdio.h>


int a[100050];
int  printValue(int n)
{
int i;
a[0]=0;
a[1]=1;
for(i=2;i<=100050;i++)
{
a[i]=(a[i-1]+a[i-2])%10000;
}
return a[n%15000]%10000;
}
int main()
{
int n;
while(scanf("%d",&n) && n != -1)
{
printf("%d\n",printValue(n));
}
return 0;
}

 

0 0
原创粉丝点击