Hat's Fibonacci
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13867 Accepted Submission(s): 4658
Problem Description
A Fibonacci sequence is calculated by adding the previous two members the sequence, with the first two members being both 1.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.
Input
Each line will contain an integers. Process to end of file.
Output
For each case, output the result in a line.
Sample Input
100
Sample Output
4203968145672990846840663646 Note: No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.
Author
戴帽子的
Recommend
Ignatius.L | We have carefully selected several similar problems for you: 1753 1865 1715 1002 2100
这题我用的java 写的
很无脑,
坑点一:大数数组要初始化,否则报异常
坑点二:数组要开到10000,开到7000就报错。
import java.math.BigDecimal;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
BigDecimal [] a=new BigDecimal[7006];
int i,j;
for(i=0;i<7006;i++)
{
if(i<4)
a[i]=new BigDecimal(1);
else
a[i]=new BigDecimal(0);
}
for(i=4;i<7006;i++)
{
a[i]=a[i].add(a[i-1]);
a[i]=a[i].add(a[i-2]);
a[i]=a[i].add(a[i-3]);
a[i]=a[i].add(a[i-4]);
}
Scanner in=new Scanner(System.in);
while(in.hasNext())
{
int n=in.nextInt();
System.out.println(a[n-1]);
}
}
}
下面是别人写的C++版:
基本思路:
用一个二维数组存数列,每一个数组单元可以存4位,亦可以存1位,理论上可以存10位,因为int类型4个字节,21亿多
用一个数组存结果的位数,注意进位和最后的进位。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<string>
#include<iostream>
#define exp 1e-10
using namespace std;
const int N = 7061;
const int inf = 2147483647;
const int mod = 2009;
int s[N][504],l[N];
int main()
{
int n,i,j;
s[1][0]=s[2][0]=s[3][0]=s[4][0]=1;
l[1]=l[2]=l[3]=l[4]=1; // 每一个数的位数
for(i=5;i<N;i++)
{
for(j=0;j<l[i-1];j++)
{
s[i][j]+=s[i-1][j]+s[i-2][j]+s[i-3][j]+s[i-4][j];
s[i][j+1]+=s[i][j]/10000; // 处理进位
s[i][j]%=10000; // 每位存4个数
}
while(s[i][j]>0) //处理最后的进位
{
s[i][j+1]+=s[i][j]/10000;
s[i][j]%=10000;j++;
}
l[i]=j;
}
while(~scanf("%d",&n))
{
printf("%d",s[n][l[n]-1]);
for(i=l[n]-2;i>=0;i--)
printf("%4.4d",s[n][i]);
puts("");
}
return 0;
}
验证了一个数组单元最多能存多少位? 8位
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<string>
#include<iostream>
#define exp 1e-10
using namespace std;
const int N = 7061;
const int inf = 2147483647;
const int mod = 2009;
const int M=100000000;
int s[N][504],l[N];
int main()
{
int n,i,j;
s[1][0]=s[2][0]=s[3][0]=s[4][0]=1;
l[1]=l[2]=l[3]=l[4]=1; // 每一个数的位数
for(i=5;i<N;i++)
{
for(j=0;j<l[i-1];j++)
{
s[i][j]+=s[i-1][j]+s[i-2][j]+s[i-3][j]+s[i-4][j];
s[i][j+1]+=s[i][j]/M; // 处理进位
s[i][j]%=M; // 每位存4个数
}
while(s[i][j]>0) //处理最后的进位
{
s[i][j+1]+=s[i][j]/M;
s[i][j]%=M;j++;
}
l[i]=j;
}
while(~scanf("%d",&n))
{
printf("%d",s[n][l[n]-1]);
for(i=l[n]-2;i>=0;i--)
printf("%8.8d",s[n][i]);
printf("\n");
}
return 0;
}