- #include <stdio.h>
- #include <time.h>
- long Nth1(long x)
- {
- return x<1?0:x+Nth1(x-1);
- }
- long Nth2(long x)
- {
- struct STACK{long n,f;char b;STACK *nxt;}rt,*sp,*md;
- sp=&rt,sp->n=x,sp->b=0;
- lab:
- if(sp->n<1)sp->f=0;
- else
- {
- (md=new STACK,md->n=sp->n-1,md->b=1,md->nxt=sp,sp=md);
- goto lab;
- bak:
- (md=sp->nxt,md->f=sp->f+md->n,delete sp,sp=md);
- }
- if(sp->b)goto bak;
- return rt.f;
- }
- long Nth3(long x)
- {
- struct STACK{long n,f;char b;}stk[120];
- short sp=0;
- stk[sp].n=x,stk[sp].b=0;
- lab:
- if(stk[sp].n<1)stk[sp].f=0;
- else
- {
- sp++;
- stk[sp].n=stk[sp-1].n-1,stk[sp].b=1;
- goto lab;
- bak:
- sp--;
- stk[sp].f=stk[sp+1].f+stk[sp].n;
- }
- if(stk[sp].b)goto bak;
- return stk->f;
- }
- int main()
- {
- clock_t t1,t2;
- for(char t=0;t<10;t++)
- {
- t1=clock();
- for(long i=0;i<100000;i++)Nth1(100);
- t2=clock();
- printf("%7.3lf\\n",(t2-t1)/1000.0);
- }
- printf("\\n");
- for(char t=0;t<10;t++)
- {
- t1=clock();
- for(long i=0;i<100000;i++)Nth2(100);
- t2=clock();
- printf("%7.3lf\\n",(t2-t1)/1000.0);
- }
- printf("\\n");
- for(char t=0;t<10;t++)
- {
- t1=clock();
- for(long i=0;i<100000;i++)Nth3(100);
- t2=clock();
- printf("%7.3lf\\n",(t2-t1)/1000.0);
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/160920135926.html
来源: http://www.codesnippet.cn/detail/160920135926.html