Method:
Analyze the problem with cases 1, 2, 3, 4 and if needed, 5. You'll soon find out that it's about even positioned Fibonacci numbers.
#include <stdio.h> #include <stdlib.h> #include <string.h> char res[1000000]; typedef struct bNum { int size; char val[2000]; } BigNum; void setNum(char *val, BigNum *pThis) { strcpy(pThis->val,val); pThis->size=strlen(val); } char *getNum(BigNum *pThis) { return pThis->val; } int addNum(BigNum *p1, BigNum *p2, BigNum *p3) { int i, j, k, car=0, cur; for (i=p1->size-1, j=p2->size-1, k=0 ; i>=0 || j>=0 ; i--, j--, k++) { cur = (i>=0?p1->val[i]:'0') + (j>=0?p2->val[j]:'0') + car - 96; if (cur>9) { car=1; res[k]=(cur-10)+'0'; } else { car=0; res[k]=cur+'0'; } } if (car) { res[k++]='1'; } p3->size=k; for (--k, i=0 ; k>=0 ; k--, i++) { p3->val[i]=res[k]; } p3->val[i]='\0'; } BigNum fibs[5000]; int main() { int i, n; setNum("1",&fibs[1]); setNum("1",&fibs[2]); for (i=3 ; i<=4001 ; i++) { addNum(&fibs[i-1],&fibs[i-2],&fibs[i]); } while (scanf("%d",&n) && n) { printf("%s\n",getNum(&fibs[2*n])); } return 0; }
No comments:
Post a Comment
Post your comment here. If you want to say something about programming problems, scripts, software etc, please try to be as descriptive as possible.