本题采用链表(n<int)占用空间小但在处理大的数时时间较长。望那位高手指点,用较短的时间又处理较大的数。
联系我:许夏,gordon772@yahoo.com.cn 多谢!
程序如下:
#include<stdio.h>
#include<malloc.h>
struct number
{ int data;
struct number *next;
}num;
struct number *create(int n) /*从个位到高位循环*/
{ int i=1,t,flag=0;
struct number *head,*r,*p,*s;
head=(struct number *)malloc(sizeof(num)) ;
head->next=NULL;
s=(struct number *)malloc(sizeof(num));
if(head->next==NULL)
{ head->next=s;head->data=0; }
head->next->data=1;
s->next=NULL;
while(i<=n) /*先乘后加*/
{ r=head->next;
while(r!=NULL)
{ t=r->data*=i; flag=0;
if(t>9&&r->next==NULL)
{ r->data=t%10; t/=10;
s=(struct number *)malloc(sizeof(num));
s->data=t%10; s->next=NULL;
r->next=s; r=s;
t/=10;
while(t>0)
{ s=(struct number *)malloc(sizeof(num));
s->data=t%10; s->next=NULL;
r->next=s; r=s;
t/=10;
}
}
r=r->next;
}
p=head->next;
while(p!=NULL)
{
t=p->data;
if(t>9)
{
p->data=t%10;
t/=10;
p=p->next; /*注重和的[··]关系*/
p->data+=t;
if(p->data>9)
{ flag=p->data;
p->data=flag%10;
flag/=10;
p->next->data+=flag; /*连续进两位以上*/
}
}
while(t>9&&p->next==NULL)
{ if(t>0)
{ p->data=t%10; t/=10;
s=(struct number *)malloc(sizeof(num));
s->data=t%10; s->next=NULL;
p->next=s; p=s;
t/=10;
}
}
p=p->next;
}
i++;
}
head=head->next; /*[··]*/
return head;
}
void disp(struct number *head) /*输处联表*/
{ while(head!=NULL)
{ printf("%d",head->data);
head=head->next;
}
printf("\n");
}
struct number *move(struct number *h) /*链表倒置*/
{ struct number *p,*q,*r=h;
q=h->next;p=h;
while(q!=NULL)
{ r=q->next; q->next=p;
p=q; q=r;
}
h->next=NULL;
h=p;
return(h);
}
main()
{ int d;
struct number *h,*p;
printf("Please input the N! number :");
scanf("%d",&d);
if(d==0)
{ printf("\nThe Result is : %d\n",d+1);
return 0;
}
h=create(d);
h=move(h);
printf("\nThe Result is : ");
disp(h);
printf("\n");
}
点这里下载附件
Word教程网 | Excel教程网 | Dreamweaver教程网 | Fireworks教程网 | PPT教程网 | FLASH教程网 | PS教程网 |
HTML教程网 | DIV CSS教程网 | FLASH AS教程网 | ACCESS教程网 | SQL SERVER教程网 | C语言教程网 | JAVASCRIPT教程网 |
ASP教程网 | ASP.NET教程网 | CorelDraw教程网 |