Fibonacci Numbers Time Limit: 1 Second Memory Limit: 32768 KB
A Fibonacci sequence is calculated by adding the previous two members of the sequence, with the first two members being both 1.
f(1) = 1, f(2) = 1, f(n > 2) = f(n - 1) + f(n - 2)
Your task is to take a number as input, and print that Fibonacci number.
Sample Input
100
Sample Output
354224848179261915075
Note:
No generated Fibonacci number in excess of 1000 digits will be in the test data, i.e. f(20) = 6765 has 4 digits.
高精度加法计算的问题,主要有一个问题就是空间复杂度,时间复杂度过得去,但是这道题第一次提交时,我却超了内存,后来我只是加了三句delete语句就A了,我这才发现原来delete语句是这么重要(以前都没用过),仅仅是加了三句delete就使内存不超了。。。下面是A了的代码,少一句delete都A不了!!!
代码:
语言:c++
#include<iostream> #include<cstring> using namespace std; int main() { char *m1,*m2,*m3; long n; m1=new char[1010*sizeof(char)]; m2=new char[1010*sizeof(char)]; char *addition(char *m1,char *m2); while(cin>>n) { m1[0]='1'; m1[1]='/0'; m2[0]='1'; m2[1]='/0'; if(n==1||n==2) cout<<1<<endl; else { for(int i=3;i<=n;++i) { m3=addition(m1,m2); strcpy(m1,m2); strcpy(m2,m3); delete m3;//第一条delete } cout<<m2<<endl; } } return 0; } char *addition(char *m1,char *m2) { int *str2int(char *str); int check(int *a,int n); char *int2str(int *a,int n); int len1=strlen(m1),len2=strlen(m2),len,i,*t1,*t2; len=(len1>=len2)?len1:len2; t1=str2int(m1); t2=str2int(m2); for(i=len1;i<=len;++i) t1[i]=0; for(i=len2;i<=len;++i) t2[i]=0; for(i=0;i<len;++i) t1[i]+=t2[i]; delete t2;//第二条delete len=check(t1,len); return int2str(t1,len); } int *str2int(char*str) { int len=strlen(str); int *a=new int[(len+1)*sizeof(int)]; for(int i=0;i<len;++i) a[i]=int(str[len-1-i])-'0'; return a; } char *int2str(int *a,int n) { int len=n; char *str=new char[(len+1)*sizeof(char)]; for(int i=0;i<len;++i) str[i]=char(a[len-1-i])+'0'; str[len]='/0'; delete a;//第三条delete return str; } int check(int *a,int n) { int len=n,i; while(a[len-1]==0&&len>1) --len; for(i=0;i<len;++i) { if(a[i]>=10) { a[i+1]+=a[i]/10; a[i]%=10; } } if(a[i]!=0) len=i+1; return len; }